Question of the aggregate function

Hi, I have question about the ability to write simple a selection (instead of select Select).
I have units with members and I want unity with the least number of members. Is possible to units with the same number of members, in this case, I get a random of these units.
It's my version "select Select:
Select min (members_count)
de)
Select United Nations. UNIT_ID,
County (me. Members_count MEMBER_ID)
members of the self,
units of the United Nations
where me. UNIT_ID is the United Nations. UNIT_ID
United Nations Group. UNIT_ID
order of members_count
)
where rownum = 1
;
Thanks for your help, Petr

If I have understood correctly, you should be able to do it like this

select min(unit_id) keep(dense_rank first order by count(*))
from members group by unit_id

Best regards

Maxim

Tags: Database

Similar Questions

  • Bug with the aggregate function and no group

    When I run the following query:
    with the_table as
    (
      select 1 as id, 100 as cost from dual
      union all select 2 as id, 200 as cost from dual
      union all select 3 as id, 300 as cost from dual
      union all select 4 as id, 400 as cost from dual
      union all select 5 as id, 500 as cost from dual
    )
    select id, cost
    from
    (
      select id, cost
      from the_table
      --
      union all
      --
      select 0 as id, sum(cost) as cost
      from the_table
      where 0 = 1
      -- group by 1
    )
    order by id;
    I get this result:
    ID    COST
    --  ------
     0  <null>     
     1     100
     2     200
     3     300
     4     400
     5     500
    However, when I "uncomment" the line "Group 1", the query works as expected (without the id = rank 0).

    This occurs even when "the_table" is an array.

    Someone else comes through this (and if so, how long is a problem)?

    The database is 11.2.0.2.0 64-bit.

    EDIT: It also happens without a Union - the following returns a single line (with null 0 and cost of id) without the Group By and no line with her:
    select id, cost
    from
    (
      select 0 as id, sum(cost) as cost
      from 
      (
        select 1 as id, 100 as cost from dual
        union all select 2 as id, 200 as cost from dual
        union all select 3 as id, 300 as cost from dual
        union all select 4 as id, 400 as cost from dual
        union all select 5 as id, 500 as cost from dual
      )
      where 0 = 1
      -- group by 1
    )
    order by id
    Edited by: Donbot February 15, 2012 10:29

    Donbot wrote:
    Someone else comes through this (and if so, how long is a problem)?

    The database is 11.2.0.2.0 64-bit.

    This is a documented behavior.

    http://docs.Oracle.com/CD/E11882_01/server.112/e26088/functions003.htm#SQLRF20035

    "
    All except COUNT (*) GROUPING and GROUPING_ID aggregate functions ignore NULL values. You can use the NVL function in the argument of an aggregation function to substitute a value for a null value. COUNTY and REGR_COUNT never return null, but return a number or zero. For all remaining functions of aggregation, * if the DataSet contains no line, * or if it contains only the rows with NULL values as arguments to the aggregate function, * then the function returns null.*
    "

  • analytical function and the aggregate function

    What are the analytical function and the aggregate function. What is the difference between them?

    Hello

    Analytic Functions : -.

    Analytical functions calculate a value of aggregation based on a group of lines. They differ from aggregate functions because they return several rows for each group. The Group of rows is called a window and is defined by the analytic_clause. For each line, a sliding window of lines is defined. The window determines the range of lines used for the calculations for the current line. Window sizes can be based on a physical number of rows or a logic as the time interval.
    Analytical functions are the last set of operations performed in a query with the exception of the last ORDER BY clause. Every joint and every WHERE, GROUP BY and HAVING clauses are met before the analytical functions are handled. As a result, analytic functions can only appear in the select list or the ORDER BY clause.
    Analytical functions are commonly used to calculate cumulative aggregates, moving, centered and considered.

    Aggregate functions : -.

    Aggregate functions return a line of single result based on the groups of lines, rather than on the unique lines. Aggregate functions can appear in selection lists, as well as in the HAVING and ORDER BY clauses. They are commonly used with the GROUP BY clause in a SELECT statement, where Oracle Database splits the rows in a table when asked or seen in groups. In a query that contains a GROUP BY clause, the select list items can be aggregation functions, GROUP BY constant expressions or expressions involving one of them. Oracle applies the functions of aggregation for each group of rows and returns a single result for each group line.
    If you omit the GROUP BY clause, Oracle then applies any aggregate functions in the select list for all rows in the table queried or the view. You use aggregate functions in the HAVING clause to eliminate groups of the output based on the results of aggregate functions, rather than the values of the individual lines of the queried table or view.

    Let me know if you feel any problem understanding.
    Thank you.

    Published by: varun4dba on January 27, 2011 15:32

  • A question about the analytical function used with the GROUP BY clause in SHORT

    Hi all

    I created the following table named myenterprise
    CITY       STOREID    MONTH_NAME TOTAL_SALES            
    ---------- ---------- ---------- ---------------------- 
    paris      id1        January    1000                   
    paris      id1        March      7000                   
    paris      id1        April      2000                   
    paris      id2        November   2000                   
    paris      id3        January    5000                   
    london     id4        Janaury    3000                   
    london     id4        August     6000                   
    london     id5        September  500                    
    london     id5        November   1000
    If I want to find which is the total sales by city? I'll run the following query
    SELECT city, SUM(total_sales) AS TOTAL_SALES_PER_CITY
    FROM myenterprise
    GROUP BY city
    ORDER BY city, TOTAL_SALES_PER_CITY;
    that works very well and produces the expected result, i.e.
    CITY       TOTAL_SALES_PER_CITY   
    ---------- ---------------------- 
    london     10500                  
    paris      17000            
    Now in one of my books SQL (Mastering Oracle SQL) I found another method by using the SUM, but this time as an analytic function. Here's what the method of the book suggests as an alternative to the problem:
    SELECT city, 
           SUM(SUM(total_sales)) OVER (PARTITION BY city) AS TOTAL_SALES_PER_CITY
    FROM myenterprise
    GROUP BY city
    ORDER BY city, TOTAL_SALES_PER_CITY;
    I know that the analytic functions are executed after the GROUP BY clause has been transformed completely and Unlike regular aggregate functions, they return their result for each line belonging to the partitions specified in the partition clause (if there is a defined partition clause).

    Now my problem is that I do not understand what we have to use two functions SUM? If we only use one only, i.e.
    SELECT city, 
           SUM(total_sales) OVER (PARTITION BY city) AS TOTAL_SALES_PER_CITY
    FROM myenterprise
    GROUP BY city
    ORDER BY city, TOTAL_SALES_PER_CITY;
    This generates the following error:
    Error starting at line 2 in command:
    SELECT city, 
           SUM(total_sales) OVER (PARTITION BY city) AS TOTAL_SALES_PER_CITY
    FROM myenterprise
    GROUP BY city
    ORDER BY city, TOTAL_SALES_PER_CITY
    Error at Command Line:2 Column:11
    Error report:
    SQL Error: ORA-00979: not a GROUP BY expression
    00979. 00000 -  "not a GROUP BY expression"
    *Cause:    
    *Action:
    The error is generated for the line 2 column 11 which is, for the expression SUM (total_sales), well it's true that total_sales does not appear in the GROUP BY clause, but this should not be a problem, it has been used in an analytical function, so it is evaluated after the GROUP BY clause.

    So here's my question:

    Why use SUM (SUM (total_sales)) instead of SUM (total_sales)?


    Thanks in advance!
    :)





    In case you are interested, that's my definition of the table:
    DROP TABLE myenterprise;
    CREATE TABLE myenterprise(
    city VARCHAR2(10), 
    storeid VARCHAR2(10),
    month_name VARCHAR2(10),
    total_sales NUMBER);
    
    INSERT INTO myenterprise(city, storeid, month_name, total_sales)
      VALUES ('paris', 'id1', 'January', 1000);
    INSERT INTO myenterprise(city, storeid, month_name, total_sales)
      VALUES ('paris', 'id1', 'March', 7000);
    INSERT INTO myenterprise(city, storeid, month_name, total_sales)
      VALUES ('paris', 'id1', 'April', 2000);
    INSERT INTO myenterprise(city, storeid, month_name, total_sales)
      VALUES ('paris', 'id2', 'November', 2000);
    INSERT INTO myenterprise(city, storeid, month_name, total_sales)
      VALUES ('paris', 'id3', 'January', 5000);
    INSERT INTO myenterprise(city, storeid, month_name, total_sales)
      VALUES ('london', 'id4', 'Janaury', 3000);
    INSERT INTO myenterprise(city, storeid, month_name, total_sales)
      VALUES ('london', 'id4', 'August', 6000);
    INSERT INTO myenterprise(city, storeid, month_name, total_sales)
      VALUES ('london', 'id5', 'September', 500);
    INSERT INTO myenterprise(city, storeid, month_name, total_sales)
      VALUES ('london', 'id5', 'November', 1000);
    Edited by: dariyoosh on April 9, 2009 04:51

    It is clear that thet Analytics is reduntant here...
    You can even use AVG or any analytic function...

    SQL> SELECT city,
      2         avg(SUM(total_sales)) OVER (PARTITION BY city) AS TOTAL_SALES_PER_CITY
      3  FROM myenterprise
      4  GROUP BY city
      5  ORDER BY city, TOTAL_SALES_PER_CITY;
    
    CITY       TOTAL_SALES_PER_CITY
    ---------- --------------------
    london                    10500
    paris                     17000
    
  • Performance of the aggregate function.

    Hello

    Version 11.2.0 Oracle

    I'm not a PL/SQL Developer, however, I decided to write this aggregate out function. Oracle has it but I tried TimesTen database in memory that does not yet function stddev.

    The code is as follows:
    CREATE OR REPLACE TYPE MyStddevImpl AS OBJECT
    (
      v_power NUMBER, -- sum(power^2) of the column
      v_sum   NUMBER, -- average value
      v_iteration NUMBER, -- count(1)
    
      STATIC FUNCTION ODCIAggregateInitialize(sctx IN OUT MyStddevImpl)
        RETURN number,
    
      MEMBER FUNCTION ODCIAggregateIterate(self IN OUT MyStddevImpl,
        value IN number)
        RETURN number,
    
      MEMBER FUNCTION ODCIAggregateTerminate(self IN MyStddevImpl,
        returnValue OUT number, flags IN number)
        RETURN number,
    
      MEMBER FUNCTION ODCIAggregateMerge(self IN OUT MyStddevImpl,
       ctx2 IN MyStddevImpl)
       RETURN number
    );
    /
    show error
    
    CREATE OR REPLACE TYPE BODY MyStddevImpl
    AS
    STATIC FUNCTION ODCIAggregateInitialize(sctx IN OUT MyStddevImpl)
    RETURN number
    AS
    BEGIN
      sctx := MyStddevImpl(0,0,0);
      RETURN ODCIConst.Success;
    END;
    
    MEMBER FUNCTION ODCIAggregateIterate(self IN OUT MyStddevImpl, value IN number)
    RETURN number
    AS
    BEGIN
      self.v_sum   := self.v_sum + value;   -- used to get averages
      self.v_power := self.v_power + power(value,2);
      self.v_iteration := self.v_iteration + 1;  -- total  number of rows
      return ODCIConst.Success;
    END;
    
    MEMBER FUNCTION ODCIAggregateTerminate(self IN MyStddevImpl, returnValue OUT
                                           number, flags IN number)
    RETURN number
    AS
      v_avg number;
    BEGIN
      v_avg :=  self.v_sum/self.v_iteration;   -- this is the average value
       -- sqrt((sum(power(amount_sold,2))-(count(1)*power(avg(amount_sold),2)))/(count(1)-1))
      returnValue := sqrt((self.v_power - (self.v_iteration * power(v_avg,2))) /(self.v_iteration-1));
      RETURN ODCIConst.Success;
    EXCEPTION
      WHEN VALUE_ERROR
      THEN
        RETURN ODCIConst.error;
    END;
    
    MEMBER FUNCTION ODCIAggregateMerge(self IN OUT MyStddevImpl, ctx2 IN
    MyStddevImpl)
    RETURN number
    AS
    BEGIN
     RETURN ODCIConst.Success;
    END;
    END;
    /
    show error
    CREATE OR REPLACE FUNCTION MyStddev (input NUMBER)
    RETURN number
    AGGREGATE USING MyStddevImpl;
    /
    show error
    exit
    Now, it works very well and returns the results OK.
    select mystddev(amount_sold) AS "My standard deviation", stddev(amount_sold) from sales;
    
    My standard deviation STDDEV(AMOUNT_SOLD)
    --------------------- -------------------
                259.78049           259.78049
    The problem I have is that it takes 10.5 sec to run
     select mystddev(amount_sold) from ssdtester.sales;
    
    MYSTDDEV(AMOUNT_SOLD)
    ---------------------
               273.172955
    
    Elapsed: 00:00:10.48
    
    Execution Plan
    ----------------------------------------------------------
    Plan hash value: 1047182207
    
    ----------------------------------------------------------------------------
    | Id  | Operation          | Name  | Rows  | Bytes | Cost (%CPU)| Time     |
    ----------------------------------------------------------------------------
    |   0 | SELECT STATEMENT   |       |     1 |     5 |  1324   (1)| 00:00:16 |
    |   1 |  SORT AGGREGATE    |       |     1 |     5 |            |          |
    |   2 |   TABLE ACCESS FULL| SALES |  1000K|  4882K|  1324   (1)| 00:00:16 |
    ----------------------------------------------------------------------------
    
    
    Statistics
    ----------------------------------------------------------
              1  recursive calls
              0  db block gets
           4965  consistent gets
              0  physical reads
              0  redo size
            558  bytes sent via SQL*Net to client
            524  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
              1  rows processed
    Is there any scope to improve this code. Specifically can I use avg function in the code instead of working on myself?

    Thank you

    Mich

    Published by: Mich Talebzadeh on February 13, 2012 12:20

    >
    May I ask what is the purpose of the model of aggregate by Oracle functions if it will be row-by-row and he's not going to be effective.
    >
    Oracle online the way you did in your function.

    Your function, using the technology of data cartridges, will be called by Oracle for EACH LINE it reads each line corresponding to your query. This requires a change in context of SQL, PL/SQL, and then back to SQL. It is a very expensive operation in terms of time.

    The Oracle SQL engine is not that way for aggregate functions it provides. The functionality of data cartridge is provided to allow developers to extend Oracle to provide features that Oracle is not provde all. Use of these functions of cartridge cases, you develop may not be 'slow' because there is no equivalent Oracle to compare to. You can use the features of your new cartridge or do you without; you have no other choice.

    You should always use SQL from Oracle to do the job unless you are doing something that can be done in SQL. Then you should use of Oracle PL/SQL features (for example in BULK of treatment) to do the more complex things. Finally if you need to do something just that Oracle cannot do with out-of-the-box SQL or PL/SQL, then you turn cartridge data, custom Java or C code or other external solutions which you can interface to Oracle.

    The order of the solutions, you should look at is:
    1 SQL
    2 PL/SQL
    3 Java/C external
    4 data cartridge

    He explains a little better? (and it is frankly win again in a minute or two!)

  • Strange question before the header function call

    Hello

    I use Oracle APEX 3.2.1.00.10 with a database of Oracle 10.2.0.4. It seems that when I call some functions in an anonymous plsql block a page header before I get

    ORA-01858: a non-digit character was found here where was waiting for a digital

    errors. The functions in question accept 2 types of NUMBER and RETURNS a type NUMBER. The code works correctly PLSQL. Is there a limit on the size of a function I can call
    directly from APEX or maybe theres some type conversion happening?

    All the ideas that it is rather strange that the other functions seem to work well

    Thanks in advance!

    As Paul said, there are probably some date related code in the body of the function. The reason why it performs very well outside the APEX is perhaps because the default NLS_DATE_FORMAT value is different to what uses the APEX. Try to play with it, hope that helps.

  • BB10 simulator: questions about the clock function

    I don't know, but I have the notion that under the Simulator for BB10 the clock() function returns a value of timer resolution of the host and not the right pair

    And since

    #define CLOCKS_PER_SEC 1000000

    during the conversion of the clock in seconds it will be least bad results under windows. Because Windows there

    #define CLOCKS_PER_SEC 1000

    I want to keep constant 60 FPS and I have a code like:

    const int FRAMES_PER_SECOND = 60;
    const int SKIP_TICKS = 1000 / FRAMES_PER_SECOND;

    int GetTickCount (void)
    {
    Return MathUtils::dti ((double) clock () / CLOCKS_PER_SEC);
    }

    and the game loop is:

    int t_prev = GetTickCount();

    mbGameRunning = true;
    While (mbGameRunning)
    {
    int t = GetTickCount();

    If ((t-t_prev) > SKIP_TICKS)
    Tick();

    Draw();

    EventLoop();

    t_prev = t;
    }

    Am I missing something?

    The clock() function only increments while your program is managed by the operating system. When the operating system switches to another task, "clock" your program stops running.

    You must use:

    clock_gettime(), which is the system clock that is still running.

  • Re: Satellite A665 - 16K: touch the buttons and the question of the FN functions

    Hello

    I have a problem with the Satellite A665 - 16 k: press the buttons and FN functions. When I install pvat they stop working, but when I uninstall the pvat only some of them work.

    How to fix? Model mu has a keyboard backlight and mine has a problem?

    > When I install pvat they stop working, but when I uninstall the pvat only some of them work.
    The current situation of the article, but I would like to know what you've done in the past. As far as I know, and my own experience, FN keys can not stop working without any reason.
    Are you using the original OS from Toshiba that was preinstalled on your laptop (WIN7 64 BIT HOME PREMIUM)?

    Usually after installing fresh PVAT everything should work again. Akuma wrote install the version of the TOSHIBA Flash Cards 1.63.0.6C support utility but do it before installing PVAT.
    > Model mu has a keyboard backlight and mine has a problem?
    I m really confused that you don't know if your laptop has this keyboard or not. Have you checked laptop specification before you bought it?
    Please read the manuals for the user's document. You will find all the info on your laptop, on the use of hardware and software. Somehow, I think you don t know what you have before you.

    Anyway, the control button Z as akuma wrote. You can also change the settings of the keyboard backlight.
    Open Toshiba Assist > optimize > HWSetup. You can find it here.

  • view set or the aggregate function

    I would like to get the result of the testcase following (using a parameterized cursor) with a simple select statement.
    As far as I know, there is no set views and I couldn't solve it with a function of aggregation (lack of experience).
    The point is: I need WHERE conditions in a fairly complex nested subquery and I would like to set it as in the slider below.
    How can I achieve this?
    Thanx.

    * < testcase > *.
    create the dummy of the table (id number 4, subsist date);
    insert dummy values (1, to_date(20090807,'YYYYMMDD'));
    insert dummy values (2, to_date(20090707,'YYYYMMDD'));
    insert dummy values (3, to_date(20090607,'YYYYMMDD'));
    insert dummy values (4, to_date(20090507,'YYYYMMDD'));
    insert dummy values (5, to_date(20090407,'YYYYMMDD'));

    Set serveroutput on
    declare
    operation (low, large date date) is
    cursor curs (low, large date date) is
    Select * from where dummy subsist between low and high.
    Start
    dbms_output.put_line ('- test-');
    for rec loop curs (low, high)
    dbms_output.put_line (rec.id |) » '|| Rec.theDate);
    end loop;
    end;
    Start
    test (to_date('01012000','DDMMYYYY'), to_date('31122010','DDMMYYYY'));
    test (to_date('01052009','DDMMYYYY'), to_date('01072009','DDMMYYYY'));
    end;
    /
    * < / testcase > *.

    * < output > *.
    -TEST-
    1 07.08.2009 00:00:00
    07.07.2009 2 00:00:00
    07.06.2009 3 00:00:00
    07.05.2009 4 00:00:00
    5 07.04.2009 00:00:00
    -TEST-
    07.06.2009 3 00:00:00
    07.05.2009 4 00:00:00
    * < / output > *.

    Edited by: user7393269 the 07.08.2009 07:12

    Uh, well, Yes, of course, blush, thanks Rob.

    This example is more appropriate:
    http://asktom.Oracle.com/pls/asktom/f?p=100:11:0:P11_QUESTION_ID:906341500346611919

    My work memory as FIFO instead of LIFO, regarding recentness of examples, I remember, it seems ;)

  • Question of the analytic function

    Hello

    SQL> create  table myphone
      2  (phone varchar2(20),
      3   username varchar2(20));
    
    
     insert into myphone VALUES (11,'A');
     insert into myphone VALUES (120,'B');
     insert into myphone VALUES (120,'C');
     insert into myphone VALUES (133,'D');
    
    COMMIT;
    Table created.
    
    SQL> SQL> SQL> 
    1 row created.
    
    SQL> 
    1 row created.
    
    SQL> 
    1 row created.
    
    SQL> 
    1 row created.
    
    SQL> SQL> 
    
    Commit complete.
    
    SQL> select * from myphone;
    
    PHONE                USERNAME
    -------------------- --------------------
    11                   A
    120                  B
    120                  C
    133                  D
    
    SQL> 
    SQL> select phone, username , rn
      2  from (
      3        Select  phone, username ,
      4                  row_number() over (partition by phone order by username) rn
      5        from    myphone
      6  )
      7   where rn <= 2
      8   ORDER BY phone;
    
    PHONE                USERNAME                     RN
    -------------------- -------------------- ----------
    11                   A                             1
    120                  B                             1
    120                  C                             2
    133                  D                             1
    

    I need repetition of the query above, only in dual phone.

    In this case, I want to get the following lines:

    120                  B                             1

    120                  C                             2

    Please notify

    Thank you

    Select phone, username, rn

    de)

    Select phone, username.

    ROW_NUMBER() on rn (partition by order phone by user name).

    Count() on cnt (partition by phone)

    of myphone

    )

    where rn<=>

    and cnt > 1

    ORDER BY phone;

    Not tested

  • Handle null values in the aggregate function

    Dear Experts,

    Here's my query

    SELECT sum (nvl (amount, 0)) + 50 AS TXN_PER_DAY_AMNT,

    COUNT (*) AS TRAN_LOG_TABLE TXN_CNT_PER_DAY

    (TRUNC (TXNDATETIME) = TO_DATE (SYSDATE, 'DD-MM-YY'));

    Exit from the MINE

    ------------------

    TXN_PER_DAY_AMNTTXN_CNT_PER_DAY
    NULL VALUE2

    Desired output

    ------------------------------

    TXN_PER_DAY_AMNTTXN_CNT_PER_DAY
    500

    I want to treat the null value,

    If my amount is null, it should replace 0 and add my 50 amount.

    Result must be 0 + 50 = 50;

    Help, please

    Maybe

    SELECT nvl (sum (sum() 50) AS TXN_PER_DAY_AMNT,

    -case when sum(amount) is null then 0 else end of COUNT (*) AS TXN_CNT_PER_DAY

    OF TRAN_LOG_TABLE

    Concerning

    Etbin

  • Question of the ROUND function

    Hello

    No idea if this is right?

    Select (1100.55*(1/30)), ROUND ((1100.55*(1/30)), 2) to double;

    should 36.685 be 36,69 rounding?

    Thank you

    Vignesh

    Think about it:

    Select

    Round(1100.55*1/30,2)

    , round (1100.55*(1/30), 2).

    of the double

    ROUND(1100.55*1/30,2),ROUND(1100.55*(1/30),2)

    «36,69 ', ' 36,68»

    1/30 is something on 0,3333333333333333333...

    So if you force to calculate 1/30 first your result would be something about 36 684...

    If round(, 2) will end at 36,68.

    But 1100.55 can be divided by 3 without rest.

    But 1100.55 can be divided by 30 so that the result is finite (infinite not like 0.33333...) can be kept full by the number of data type.

    So, if the calculation order is 1100.55 divided by 1, then didved by 30, this would translate exactly in 36 685.

    It seems to me the use of parentheses introduced some binary float during the calculation, because it can be assumed with regard to landfills:

    Select

    dump(1100.55*1/30)

    dump (1100.55*(1/30))

    of the double

    DUMP(1100.55*1/30),DUMP(1100.55*(1/30))

    ' Type = 2 Len = 4: 193,37,69,51 Typ ',' 2 Len = 21 =: 193,37,69,50,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,97 ".

    Therefore, the result is a bit small (in this case, could be another average round in other cases) and turn therefore not lead to the expected result.

    Without the parentheses all operands are considered as numbers and so round gives the desired result.

    The reason may lie in the fact that oracle doesn't really change the bytes when converting from float to the number:

    Select

    dump (0.3)

    truck (cast (0.3f as number))

    of the double

    DUMP (0.3), DUMP (CAST(0.3FASNUMBER))

    ' Type = 2 Len = 2: 192,31 Typ ',' = 2 Len = 6: 192,31,1,1,2,21 ".

    Post edited by: chris227 corrected and extended

    Post edited by: chris227

  • String and the aggregate function

    Hi all
    Suppose that in the HR schema example, I want to count all the employee table names that start by the of the. The following queries employees with this name:
    SQL> select first_name,job_id,count(first_name) from employees where first_name
    like 'S%' group by first_name, job_id;
    
    FIRST_NAME           JOB_ID     COUNT(FIRST_NAME)
    -------------------- ---------- -----------------
    Sundita              SA_REP                     1
    Samuel               SH_CLERK                   1
    Shelli               PU_CLERK                   1
    Sigal                PU_CLERK                   1
    Shelley              AC_MGR                     1
    Steven               AD_PRES                    1
    Susan                HR_REP                     1
    Sarath               SA_REP                     1
    Shanta               ST_MAN                     1
    Steven               ST_CLERK                   1
    Stephen              ST_CLERK                   1
    
    FIRST_NAME           JOB_ID     COUNT(FIRST_NAME)
    -------------------- ---------- -----------------
    Sundar               SA_REP                     1
    Sarah                SH_CLERK                   1
    
    13 rows selected.
    How to query number of employees who have first names beginning by the of '?

    Best regards
    Valerie
    Also I want to query first name and number of count, is this possible?
    

    I think you want:

    SELECT FIRST_NAME, COUNT (*)
    EMPLOYEES
    WHERE NAME LIKE %'
    ROLLUP GROUP ((FIRST_NAME))

  • Query SQL using Group by and the aggregate function

    Hi all

    I need your help in writing a SQL query to achieve the following objectives.

    Scenario:

    I have a table with 3 columns. There are 3 possible values for col3 - success, failure, and error.
    Now I need a query that can give me the summary figures for distinct values for col3 for each GROUP BY col1 and col2 values. When there is no values for col3, then it should return ZERO count.

    The example data:

    Col1 Col2 Col3

    success of ABC 01
    success of ABC 02
    success of ABC 01
    ABC 01 failure
    ABC 01 error
    ABC 02 failure
    ABC 03 error
    XYZ 07 failure

    Power required:

    C1 c2 s_cnt F_cnt E_cnt (title)
    ABC 01 2 1 1
    ABC 02 1 1 0
    03 0 0 1 ABC
    XYZ 07 0 1 0

    s_cnt = number of success; F_cnt = number of failure; E_cnt = number of errors

    Please note that the exit should have 5 columns col1, col2, group of (col1, col2) count (success), group of (col1, col2) count (failure), group of (col1, col2) count (error)
    and wherever there are n ROWS, then it should return ZERO.

    Thanks in advance.

    Kind regards
    Shiva

    Hi, Shiva,

    Welcome to the forum!

    Here's one way:

    SELECT       col1
    ,       col2
    ,       COUNT ( CASE
                          WHEN  col3 = 'success'
                    THEN  1
                      END
                 )          AS s_cnt
    ,       COUNT ( CASE
                          WHEN  col3 = 'failure'
                    THEN  1
                      END
                 )          AS f_cnt
    ,       COUNT ( CASE
                          WHEN  col3 = 'Error'
                    THEN  1
                      END
                 )          AS e_cnt
    FROM       table_x
    GROUP BY  col1
    ,            col2
    ;
    

    Whenever you have a problem, post a small example data (CREATE TABLE and only relevant columns, INSERT statements). If you do not, then don't expect answers, you can get to test.
    Also post the results desired from these data.

  • Question about the CAST function

    Hi all

    I have two tables that have the same columns and the different type of data. I have to create a Union to see all these paintings, but want to change the data type of number (6) in the view. I couldn't do. Could someone please help me out here.

    Thanks in advance!


    SQL > desc t1;
    Name Null? Type
    ----------------------------------------------------------------- -------- ------------
    COL1 NUMBER (3)

    SQL > desc t2;
    Name Null? Type
    ----------------------------------------------------------------- -------- ------------
    COL1 NUMBER (6)

    SQL > create or replace view t12
    2 as
    3 select cast (col1 as col1 number (6)) from t1
    4 Union all the
    5 Select cast (col1 as number (6)) t2 col1;

    Created view.

    SQL > desc t12
    Name Null? Type
    ----------------------------------------------------------------- -------- -------------
    COL1 NUMBER


    SQL > create or replace view t12
    2 as
    3 select cast (col1 as col1 number (6)) from t1
    4 Union all the
    5. Select col1 in t2;

    SQL > desc t12
    Name Null? Type
    ----------------------------------------------------------------- -------- --------------
    COL1 NUMBER


    SQL > create or replace view t12
    2 as
    3 select cast (col1 as col1 varchar2 (6)) from t1
    4 Union all the
    5 Select cast (col1 as varchar2 (6)) t2 col1;

    Created view.

    SQL > desc t12
    Name Null? Type
    ----------------------------------------------------------------- -------- -----------------------
    COL1 VARCHAR2 (6)

    Hello

    As others have mentioned, no doubt regardless of whether the column is a NUMBER (6) or the NUMBER without limitation.

    In case it matters, however, you can get the desired results by masking the UNION within a subquery:

    CREATE OR REPLACE VIEW t12
    AS
    SELECT     CAST (col1 AS NUMBER(6))  AS col1
    FROM     (            SELECT   col1     FROM t1
         UNION ALL  SELECT   col1     FROM t2
         );
    

Maybe you are looking for