SQL question: group by horizontally

Hi,
I'm having trouble figuring out a way to display the result of a join in the following tabular format. Can someone please assist?
SQL> select * from tab1;
GNAME SNO
ABC 5
DEF 2
ABC 3
SQL> select * from tab2;
GNAME SNO
ABC 10
XYZ 5
DEF 15
My current output using a UNION ALL:
SQL> select gname, count(*) sno1 from tab1 group by gname
2 union all
3 select gname, count(*) sno2 from tab2 group by gname;
GNAME SNO1
ABC 2
DEF 1
ABC 1
DEF 1
XYZ 1
The output I'm expecting:
GNAME SNO1          SNO2
ABC 2 1
DEF 1 1
XYZ 0 1
Thanks in advance.

szsl wrote:
My current output using a UNION ALL:
SQL> select gname, count(*) sno1 from tab1 group by gname
2 union all
3 select gname, count(*) sno2 from tab2 group by gname;you need this to identify all distinct gnames.
with tab1 as (
select 'ABC' as gname, 5 as sno from dual union all
select 'DEF' as gname, 2 as sno from dual union all
select 'ABC' as gname, 3 as sno from dual
), tab2 as (
select 'ABC' as gname, 10 as sno from dual union all
select 'XYZ' as gname, 5 as sno from dual union all
select 'DEF' as gname, 15 as sno from dual
select a.gname, sum( case when tab1.gname is not null then 1 else 0 end) as cnt_1,
sum( case when tab2.gname is not null then 1 else 0 end) as cnt_2
from (
  select distinct gname from (select gname from tab1 union all select gname from tab2)
) a
left join tab1 on tab1.gname = a.gname
left join tab2 on tab2.gname = a.gname
group by a.gname
order by a.gname
;output:
GNAME CNT_1 CNT_2
ABC       2     2
DEF       1     1
XYZ       0     1

Similar Messages

  • Urgent SQL question : how to flip vertical row values to horizontal ?

    Hello, Oracle people !
    I have an urgent SQL question : (simple for you)
    using SELECT statement, how to convert vertical row values to horizontal ?
    For example :
    (Given result-set)
    MANAGER COLUMN1 COLUMN2 COLUMN3
    K. Smith ......1
    K. Smith ...............1
    K. Smith ........................1
    (Needed result-set)
    MANAGER COLUMN1 COLUMN2 COLUMN3
    K. Smith ......1 .......1 .......1
    I know you can, just don't remeber how and can't find exactly answer I'm looking for. Probably using some analytic SQL function (CAST OVER, PARTITION BY, etc.)
    Please Help !!!
    Thanx !
    Steve.

    scott@ORA92> column vice_president format a30
    scott@ORA92> SELECT f.VICE_PRESIDENT, A.DAYS_5, B.DAYS_10, C.DAYS_20, D.DAYS_30, E.DAYS_40
      2  FROM   (select t2.*,
      3                row_number () over
      4                  (partition by vice_president
      5                   order by days_5, days_10, days_20, days_30, days_40) rn
      6            from   t2) f,
      7           (SELECT T2.*,
      8                row_number () over (partition by vice_president order by days_5) RN
      9            FROM   T2 WHERE DAYS_5 IS NOT NULL) A,
    10           (SELECT T2.*,
    11                row_number () over (partition by vice_president order by days_10) RN
    12            FROM   T2 WHERE DAYS_10 IS NOT NULL) B,
    13           (SELECT T2.*,
    14                row_number () over (partition by vice_president order by days_20) RN
    15            FROM   T2 WHERE DAYS_20 IS NOT NULL) C,
    16           (SELECT T2.*,
    17                row_number () over (partition by vice_president order by days_30) RN
    18            FROM   T2 WHERE DAYS_30 IS NOT NULL) D,
    19           (SELECT T2.*,
    20                row_number () over (partition by vice_president order by days_40) RN
    21            FROM   T2 WHERE DAYS_40 IS NOT NULL) E
    22  WHERE  f.VICE_PRESIDENT = A.VICE_PRESIDENT (+)
    23  AND    f.VICE_PRESIDENT = B.VICE_PRESIDENT (+)
    24  AND    f.VICE_PRESIDENT = C.VICE_PRESIDENT (+)
    25  AND    f.VICE_PRESIDENT = D.VICE_PRESIDENT (+)
    26  AND    f.VICE_PRESIDENT = E.VICE_PRESIDENT (+)
    27  AND    f.RN = A.RN (+)
    28  AND    f.RN = B.RN (+)
    29  AND    f.RN = C.RN (+)
    30  AND    f.RN = D.RN (+)
    31  AND    f.RN = E.RN (+)
    32  and    (a.days_5 is not null
    33            or b.days_10 is not null
    34            or c.days_20 is not null
    35            or d.days_30 is not null
    36            or e.days_40 is not null)
    37  /
    VICE_PRESIDENT                     DAYS_5    DAYS_10    DAYS_20    DAYS_30    DAYS_40
    Fedele Mark                                                          35473      35209
    Fedele Mark                                                          35479      35258
    Schultz Christine                              35700
    South John                                                                      35253
    Stack Kevin                                    35701      35604      35402      35115
    Stack Kevin                                    35705      35635      35415      35156
    Stack Kevin                                    35706      35642      35472      35295
    Stack Kevin                                    35707      35666      35477
    Stack Kevin                                               35667      35480
    Stack Kevin                                               35686
    Unknown                             35817      35698      35596      35363      35006
    Unknown                                        35702      35597      35365      35149
    Unknown                                        35724      35599      35370      35155
    Unknown                                                   35600      35413      35344
    Unknown                                                   35601      35451      35345
    Unknown                                                   35602      35467
    Unknown                                                   35603      35468
    Unknown                                                   35607      35475
    Unknown                                                   35643      35508
    Unknown                                                   35644
    Unknown                                                   35669
    Unknown                                                   35684
    Walmsley Brian                                 35725      35598
    23 rows selected.

  • SQL Question Bank and Answers for Practise

    Dear Readers:
    Does any one have any recommendation on SQL question bank and answers where I could practice my SQL.
    I have developed some basic knowledge of SQL thanks to the MS community, but I am looking for some additional Questions or textbook  recommendations which has questions and answers to queries for practice.
    Best Wishes,
    SQL75

    Hi,
    Refer below post.
    https://social.msdn.microsoft.com/Forums/sqlserver/en-US/446b2247-5124-49c1-90c9-b7fea0aa4f83/sql-dba-books?forum=sqlgetstarted
    Please mark solved if I've answered your question, vote for it as helpful to help other users find a solution quicker
    Praveen Dsa | MCITP - Database Administrator 2008 |
    My Blog | My Page

  • Sql question : TRUNCATE vs Delete

    hi
    this is sql question, i don't know where i should post it, so here it is.
    i just want to know the best usage of each. both commands delete records in a table, one deletes all, and the other can do the same plus option to delete specified records. if i just want to purge the table. which one is better and why? thanks

    this is crucial to my design, i need to be able to
    rollback if one of the process in the transaction
    failed, the whole transaction should rollback. if
    truncate does not give me this capability, then i have
    to consider Delete.From the Oracle manual (sans the pretty formatting):
    TRUNCATE
    Caution: You cannot roll back a TRUNCATE statement.
    Purpose
    Use the TRUNCATE statement to remove all rows from a table or cluster. By default,
    Oracle also deallocates all space used by the removed rows except that specified by
    the MINEXTENTS storage parameter and sets the NEXT storage parameter to the size
    of the last extent removed from the segment by the truncation process.
    Removing rows with the TRUNCATE statement can be more efficient than dropping
    and re-creating a table. Dropping and re-creating a table invalidates the table?s
    dependent objects, requires you to regrant object privileges on the table, and
    requires you to re-create the table?s indexes, integrity constraints, and triggers and
    respecify its storage parameters. Truncating has none of these effects.
    See Also:
    DELETE on page 16-55 and DROP TABLE on page 17-6 for
    information on other ways to drop table data from the database
    DROP CLUSTER on page 16-67 for information on dropping
    cluster tables
    Prerequisites
    To truncate a table or cluster, the table or cluster must be in your schema or you
    must have DROP ANY TABLE system privilege.

  • Derivation procedure where question group has no enterable fields

    I have a question group that has only 2 fields -> one field is derived and the field other is a non-enterable field with a default value. The field I'm trying to derive is adding the scores from a repeating question group within the same DCM. The problem is that the question group with the derived field needs to be the primary reference (it will not generate otherwise); however, since there are no enterable fields within this question group it is not recognizing any data as being entered and therefore will never derive. Is there a way to get around this? I hope I've explained my situation clearly. Thanks!

    I have a question group that has only 2 fields -> one field is derived and the field other is a non-enterable field with a default value. The field I'm trying to derive is adding the scores from a repeating question group within the same DCM. The problem is that the question group with the derived field needs to be the primary reference (it will not generate otherwise); however, since there are no enterable fields within this question group it is not recognizing any data as being entered and therefore will never derive. Is there a way to get around this? I hope I've explained my situation clearly. Thanks!

  • SQL question- on how to handle groups of records at a time.

    Hi,
    I have a sql that looks like the following:
    insert into INVALID_DATES_TMP
    (id, gid, created, t_rowid, updated)
    select id, gid, created, rowid, updated
    from TABLE1
    where fix_invalid_date_pkg.is_date_invalid('TABLE1', 'CREATED', ROWID) = 'Y';
    COMMIT;
    What the above sql does is selects all rows from TABLE1 where the CREATED column
    has invalid dates and inserts them into invalid_dates_tmp table. So we can process/fix
    those invalid dates from the temp table. Problem is our DBA said Table1 can have
    millions of rows so the above sql can be very database intensive. So, I need to
    figure out another way that may handle chunks of rows at a time from table1.
    Any ideas are appreciated!
    ThankYou,
    Radhika.

    Hallo,
    in general INSERT AS SELECT is the fastest method to insert into the table.
    Probably you can use direct load ? (Hint APPEND).
    Other options (INSERT IN LOOP or BULK + FORALL) are slower.
    I think, this method is optimal.
    Another question is, the function itself. It is not clear, whether it searches the invalid dates optimal. I suppose strong, that function uses dynamic SQL.
    Why ? It is better to search static . Or you use this function for many other columns ? Could you post the function also ?
    Regards
    Dmytro

  • Grouping ... SQL question

    I have a table name BLABLA(Bla1 int,Bla2 TEXT,index int)
    I want to select * from the tabel if the sold is not = 1
    how do I write the sql statement ?

    here is the Exception
    java.sql.SQLException: Syntax error or access violation: You have an error in your SQL syntax near '? where cat_id = ?' at line 1
    here is the code:
    public ResultSet selectCatItems(String tableName,String cat_id)
    PreparedStatement pstmt =null;
    String sql = "select * from ? where cat_id = ?";
    try{
    pstmt = Conn.prepareStatement(sql);
    pstmt.setString(1,tableName);
    pstmt.setString(2,cat_id);
    rs=pstmt.executeQuery(sql);
    exp = exp + sql;
    return rs;
    } catch (SQLException e) {  exp = exp +"<BR>  "+ e.toString(); return null; }
    Connection to the DB created in other mothods, other SQL statements working fine....

  • SQL Questions (New to Cisco)

    Hello. I work for Clarian Health in Indianapolis and am trying to learn as much as possible about the SQL databases, both AWDB and HDS so that I can handle the reporting for our Revenue Cycle Customer Service.
    I am currently working my way through the Database Schema Handbook for Cisco Unified ICM /Contact Center Enterprise & Hosted. I’m also reviewing the explanation pages that are available for the reports on WebView. During my reviews, I have noticed a few things that confuse me.
    My questions are:
    1. Why do a majority of the tables on our SQL Server start with “t_”?
    2. Why do some of the tables have data on the AWDB server but not on the HDS server, and vice versa? (Examples: t_Agent and t_Agent_Team and t_Agent_Team_Member and t_Person are blank on the HDS database but not blank on the AWDB database; but the t_Agent_Logout is blank on the AWDB database and not blank on the HDS database)
    3. When data is moved to the HDS server every 30 minutes, is it also removed from the corresponding AWDB table?
    4. In review of the agent26: Agent Consolidated Daily Report syntax info located on the WebView, 1 of the calculations uses the LoggedOnTimeToHalf from the Agent_Half_Hour table while the remaining calculations uses the same field from the Agent_Skill_Group_Half_Hour table. Can you please tell me why this is? Why would all of the percent calculations not use the data from the same table? (The % of time Agent paused and/or put a task on hold uses the Agent_Half_Hour Table. All other % calculations uses the same field from the Agent_Skill_Group_Half_Hour Table.)
    5. Also in reviewing the agent26: Agent Consolidated Daily Report syntax info, I noticed that it contains the Skill_Group table, the Agent_Half_Hour table and the Media_Routing_Domain table. Both the Skill Group table and the Agen_Half_Hour table contain links to the Media_Routing_Domain table. Which relationship/join is actually utilized for this report?
    6. Why doesn't the LoggedOnTimeToHalf field on both the Agent_Half_Hour table and the Agent_Skill_Group_Half_Hour table have the same value in them?
    7. On the agent_26: Agent Consolidated Daily Report syntax explanation page, the Agent State Times: Log on Duration says that it is derived using the Agent_Half_Hour.LoggedOnTimeToHalf field, but when i convert this field to HH:MM:SS, it does not match the actual WebView report. But, when I use the Agent_Skill_Group_Half_Hour.LoggedOnTimeToHalfHour, it does match. Which one is correct?
    8. On the agent_26: Agent Consolidated Daily Report, why does the Completed Tasks: Transfer Out contain both the TransferredOutCallsToHalf and the NetTransferredOutCallsToHalf fields? What's the difference between the two? What Transfer out data writes to each field?
    Thank you.
    Angie Combest
    Clarian Health
    [email protected]

    You need to be careful when looking at the three databases - Logger, AW, HDS - which use the same schema. But many of what appear to be tables in the AW are really views into the t_ tables in the HDS - the data is not there in the AW DB. You are right to look at the schema - but check with SQL Enterprise to understand a bit more.
    In essence, the AW DB is for configuration data and real-time data. The HDS is for historical data. You can query the AW DB for (say) Call_Type_Half_Hour data and join with the Call_Type table to resolve the call type ID into its name - but the data is really in the HDS through the view.
    The DB design is quite complex and sophisticated - many things are not obvious.
    Keep up your research.
    Regards,
    Geoff

  • SQL question - please help!

    Hi,
    I am working on a SQL, please help ms with the question
    below .... thanks
    (1)Increase by 10% salary of these captain pilots who have
    traveled more than 800,000 miles.
    Routes | | Flights | |Pilots |
    | | | | |
    #routeID | | #flightNO | |#pilotID |
    depAirportID |        |  airplaneNO| |*name |
    arrAirportID |_______/|  pilotID |\___________|*hours_in_air|
    length       |       \|  routeID |/ |*grade |
    ______________| |_____________| |*salary |
    |____________|

    If the length column in routes is in hours, and it represents
    additional hours to those shown in hours_in_air in pilots, then
    the following should work:
    UPDATE pilots
    SET salary = salary * 1.1
    WHERE pilotid in (SELECT a.pilotid
    FROM pilots a,
         (SELECT b.pilotid,sum(c.length) new_hours
          FROM flights b, routes c
          WHERE b.routeid = c.routeid
          GROUP BY b.pilotid) d
    WHERE a.pilotid = d.pilotid and
          new_hours + hours_in_air >= 80000)I suspect that you probably need to add additional criteria to
    the sub-query from flights and routes to take into account only
    flights since the hours_in_air column from pilots was last
    updated. However, your table structures do not indicate any
    date sensitivity. If the table flights is emptied every time
    hours_in_air is updated, then the query above will work.

  • SQL question for to get a top customer

    Hi All,
    I am prasanna. I have a question on SQL,to get a top customer based on year and customer name.I written query like this. But i got an error.
    select calendar_year,cust_first_name,max(sum(amount_sold)) from sales,times,customers where sales.cust_id=customers.cust_id and times.time_id=sales.time_id group  by calendar_year,cust_first_name
    The error is like this:
    *Error starting at line 1 in command:
    select calendar_year,cust_first_name,max(sum(amount_sold)) from sales,times,customers where sales.cust_id=customers.cust_id and times.time_id=sales.time_id group by calendar_year,cust_first_name
    Error at Command Line:1 Column:7
    Error report:
    SQL Error: ORA-00937: not a single-group group function
    00937. 00000 - "not a single-group group function"*
    *Cause:   
    Action:
    Thanks inadvace
    Regards,
    prasanna

    It is not clear what you want. Code below will return a customer with highest total amout sold regardless of year:
    select  calendar_year,
            cust_first_name,
            total_amount_sold max_amount_sold
      from  (
             select  calendar_year,
                     cust_first_name,
                     sum(amount_sold) total_amount_sold,
                     row_number() over(order by sum(amount_sold) desc) rn
               from  sales,
                     times,
                     customers
               where sales.cust_id=customers.cust_id
                 and times.time_id=sales.time_id
               group by calendar_year,
                     cust_first_name
      where rn = 1
    /Keep in mind, if more than one customer has that highest total amount sold and you want all such customers:
    select  calendar_year,
            cust_first_name,
            total_amount_sold max_amount_sold
      from  (
             select  calendar_year,
                     cust_first_name,
                     sum(amount_sold) total_amount_sold,
                     rank() over(order by sum(amount_sold) desc) rn
               from  sales,
                     times,
                     customers
               where sales.cust_id=customers.cust_id
                 and times.time_id=sales.time_id
               group by calendar_year,
                     cust_first_name
      where rn = 1
    /And if you want top customer for each calendar year:
    select  calendar_year,
            cust_first_name,
            total_amount_sold max_amount_sold
      from  (
             select  calendar_year,
                     cust_first_name,
                     sum(amount_sold) total_amount_sold,
                     row_number() over(partition by calendar_year order by sum(amount_sold) desc) rn
               from  sales,
                     times,
                     customers
               where sales.cust_id=customers.cust_id
                 and times.time_id=sales.time_id
               group by calendar_year,
                     cust_first_name
      where rn = 1
    /Keep in mind, if more than one have that highest total amount sold and you want all such customers:
    select  calendar_year,
            cust_first_name,
            total_amount_sold max_amount_sold
      from  (
             select  calendar_year,
                     cust_first_name,
                     sum(amount_sold) total_amount_sold,
                     rank() over(partition by calendar_year order by sum(amount_sold) desc) rn
               from  sales,
                     times,
                     customers
               where sales.cust_id=customers.cust_id
                 and times.time_id=sales.time_id
               group by calendar_year,
                     cust_first_name
      where rn = 1
    /SY.
    Edited by: Solomon Yakobson on Dec 22, 2011 9:24 AM

  • SQL 2014 - Group Membership for sysadmin permissions not working

    I am using SQL 2014 on Windows Server 2012 R2 and am running into a permission issue. During the install I specified the local server's Administrators group as well as my specific domain account to have sysadmin privileges. 
    The issue is that accounts that are a member of the local server's administrators group can't even login to SQL Server Management Studio unless they are specifically granted permissions for their account (my domain account works fine as it has a specific
    credential in SQL).
    The log just gives the following error:
    Login failed for user 'domainname\username'. Reason: Token-based server access validation failed with an infrastructure error. Check for previous errors. [CLIENT: <local machine>]
    Error: 18456, Severity: 14, State: 11.
    I haven't had this issue in previous versions. Is there something that must be done differently in 2014 to grant permissions to groups?

    Hi, something like
    this?
    Bye
    Questo post è fornito "così com'è". Non conferisce garanzie o diritti di alcun tipo. Ricorda di usare la funzione "segna come risposta" per i post che ti hanno aiutato a risolvere il problema e "deseleziona come risposta"
    quando le risposte segnate non sono effettivamente utili. Questo è particolarmente utile per altri utenti che leggono il thread, alla ricerca di soluzioni a problemi similari. ENG: This posting is provided "AS IS" with no warranties, and confers
    no rights. Please remember to click "Mark as Answer" on the post that helps you, and to click "Unmark as Answer" if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.

  • Newb question - group by sequence number range

    Hi - I'm a newb to pl/sql but am pretty familiar with t-sql and sql server.
    Here's my question:
    I have a database table with ~1.6M records, call it "a". a has two columns, id (a sequence) and status. status has three possible values: null, error and success.
    I want to write a query that will group the sequence numbers into sets of 100k and give the the count of nulls, errors and successes for that set. The output should be something like:
    set null error success
    1-100,000 x y z
    100,001-200,000 x y z
    200,001-300,000 x y z
    Can anyone point me in the right direction?

    I scaled it down with a factor 1000, and here is the idea:
    SQL> create table a
      2  as
      3   select level id
      4        , decode(mod(level,3),1,'error',2,'success',null) status
      5     from dual
      6  connect by level <= 1600
      7  /
    Tabel is aangemaakt.
    SQL> select trunc((id-1)/100)*100 + 1 lb
      2       , trunc((id-1)/100)*100 + 100 ub
      3       , count(decode(status,'error',1)) err
      4       , count(decode(status,'success',1)) success
      5       , count(decode(status,null,1)) "NULL"
      6    from a
      7   group by trunc((id-1)/100)
      8  /
            LB         UB        ERR    SUCCESS       NULL
             1        100         34         33         33
           101        200         33         34         33
           201        300         33         33         34
           301        400         34         33         33
           401        500         33         34         33
           501        600         33         33         34
           601        700         34         33         33
           701        800         33         34         33
           801        900         33         33         34
           901       1000         34         33         33
          1001       1100         33         34         33
          1101       1200         33         33         34
          1201       1300         34         33         33
          1301       1400         33         34         33
          1401       1500         33         33         34
          1501       1600         34         33         33
    16 rijen zijn geselecteerd.Regards,
    Rob.

  • SQL Question: Selecting earliest date time

    I've a table that contains multiple transactions per any given day.
    For each day of the month, I'm trying to find the earliest transaction possible.  Below is my table data:
    DATE                    |QUANTITY    |DIVISION    |  LOCATION
    01-JAN-2008 12:42:01 AM |1234        |1           |  NORTH
    01-JAN-2008 05:42:22 AM |1200        |1           |  NORTH
    01-FEB-2008 01:42:01 AM |1123        |1           |  NORTH
    01-FEB-2008 03:11:01 AM |985         |1           |  NORTH
    So the question is, how do I select the EARLIEST transaction row for each given month,
    This is my current SQL:
    select       min(DATE),
                 QUANTITY,
                 DIVISION,
                 LOCATION
                 from TABLE
                 group by QUANTITY, DIVISION, LOCATION
    DATE field is a datatype "DATE" in Oracle database
    My goal is to pretty much have the results shown as follows:
    DATE                    |QUANTITY    |DIVISION    |  LOCATION
    01-JAN-2008 12:42:01 AM |1234        |1           |  NORTH
    01-FEB-2008 01:42:01 AM |1123        |1           |  NORTH

    Hi Eric
    Use the following query:
    select    DATE,
                 QUANTITY,
                 DIVISION,
                 LOCATION
                 from TABLE
    where DATE in
    select min(DATE) from TABLE
    group by to_char(DATE,'YYYY')
    group by DATE,QUANTITY, DIVISION, LOCATION
    Hope this helps.
    Regards
    Nikhil

  • Another simple SQL question?

    Can someone help me (an SQL novice) optimize this query?
    Assume a table TRANS with four columns ACCOUNT, PURCHASE_DATE,
    ITEM_NUMBER, and QUANTITY. (Fairly self evident names, I hope.)
    I want to create a view that returns the most recent purchase
    date for each account, and the sum of all items purchase on that
    date.
    The following works, but involves a sub-query, which I think
    must be inefficient (the real table I'm working with has about
    20 million rows, returning about 1 million rows and takes
    hours!):
    select unique a.account,
    purchase_date,
    sum(quantity)
    from TRANS a,
    (select account,
    max(purchase_date) as cdate
    from TRANS
    group by account) b
    where a.account = b.account and
    a.purchase_date = b.cdate
    group by a.account;
    A second, similar query is to find the most recent purchase
    date, by account, for each item, and the total quantity of that
    item purchased on that date. But, hopefully, an answer to the
    first question will lead me in the right direction.
    Thanks!
    Bob

    Here is another batch of queries to test. The one on top is the
    only one that is drastically different from your query or
    anything that David already suggested.
    SELECT  account,
            purchase_date,
            total
    FROM    (SELECT   account,
                      purchase_date,
                      SUM (quantity) total,
                      RANK () OVER
                           (PARTITION BY account
                            ORDER BY purchase_date DESC)
                      AS rk
             FROM     trans
             GROUP BY account, purchase_date)
    WHERE    rk = 1
    ORDER BY account
    SELECT   a.account,
             a.purchase_date,
             SUM (quantity) total
    FROM     trans a,
             (SELECT   account,
                       MAX (purchase_date) cdate
              FROM     trans
              GROUP BY account) b
    WHERE    a.account = b.account
    AND      a.purchase_date = b.cdate
    GROUP BY a.account, a.purchase_date
    ORDER BY a.account
    SELECT    account,
              purchase_date,
              SUM (quantity) total
    FROM      trans a
    WHERE NOT EXISTS
              (SELECT 0
               FROM   trans b
               WHERE  b.account = a.account
               AND    b.purchase_date > a.purchase_date)
    GROUP BY  account, purchase_date
    ORDER BY  a.account
    SELECT   a.account,
             a.purchase_date,
             SUM (quantity) total
    FROM     trans a
    WHERE    a.purchase_date =
             (SELECT MAX (b.purchase_date)
              FROM   trans b
              WHERE  b.account=a.account)
    GROUP BY a.account, a.purchase_date
    ORDER BY a.account
    SELECT   a.account,
             a.purchase_date,
             SUM (quantity) total
    FROM     trans a
    WHERE    (a.account, a.purchase_date) IN
             (SELECT   b.account,
                       MAX (b.purchase_date)
              FROM     trans b
              GROUP BY b.account)
    GROUP BY a.account, a.purchase_date
    ORDER BY a.account
    SELECT   a.account,
             a.purchase_date,
             SUM (quantity) total
    FROM     trans a
    WHERE    a.purchase_date =
             (SELECT /*+ INDEX_DESC (b my_index) */
                     b.purchase_date
              FROM   trans b
              WHERE  b.account = a.account
              AND    ROWNUM = 1)
    GROUP BY a.account, a.purchase_date
    ORDER BY a.account

  • SQL query group by with concatenation

    How can i put the name of the column i concatenated in group by command?
    Example is:
    tbl_staff
    user_id     name          profile          last_name
    1     una          0001          astfirst
    2     pangalawa     0001          lastsecond
    3 pangatlo     0001          lastthird
    4 pangapat     0001          lastfourth
    5 panglima     0002          lastfifth
    tbl_work_assignment
    wa_id     handled_by     status
    10     1          active
    20     1          active
    30     2          closed
    40     3          active
    50     3          closed
    60     3          active
    If my Query is:
    select s.user_id, s.name, count(wa.wa_id)
    from tbl_staff s
    left join tbl_work_assignment wa
    on wa.handled_by = s.user_id
    where profile = '0001' and status = 'active'
    group by s.user_id, s.name
    I will get this result
    s.user_id     s.name          count(wa.wa_id)
    1          una          2
    3          pangatlo     2
    My question is:
    "HOW CAN I CONCATENATE THE 'NAME' AND 'LAST_NAME' COLUMNS AND PUT THEIR COLUMN NAME IN GROUP BY?"
    Desired Resultset is:
    s.user_id     s.name          full_name count(wa.wa_id)
    1          una          una lastfirst 2
    3          pangatlo     pangatlo lastthird 2
    I hope you understood my question.. I can explain further if its not clear. Thanks

    And the proof that Alex's last suggestion works:
    SQL> create table tbl_staff (user_id,name,profile,last_name)
      2  as
      3  select 1, 'una', '0001', 'astfirst' from dual union all
      4  select 2, 'pangalawa', '0001', 'lastsecond' from dual union all
      5  select 3, 'pangatlo', '0001', 'lastthird' from dual union all
      6  select 4, 'pangapat', '0001', 'lastfourth' from dual union all
      7  select 5, 'panglima', '0002', 'lastfifth' from dual
      8  /
    Tabel is aangemaakt.
    SQL> create table tbl_work_assignment (wa_id,handled_by,status)
      2  as
      3  select 10, 1, 'active' from dual union all
      4  select 20, 1, 'active' from dual union all
      5  select 30, 2, 'closed' from dual union all
      6  select 40, 3, 'active' from dual union all
      7  select 50, 3, 'closed' from dual union all
      8  select 60, 3, 'active' from dual
      9  /
    Tabel is aangemaakt.
    SQL> select s.user_id
      2       , s.name
      3       , s.name || ' ' || s.last_name full_name
      4       , count(wa.wa_id)
      5    from tbl_staff s
      6         left join tbl_work_assignment wa on wa.handled_by = s.user_id
      7   where profile = '0001'
      8     and status = 'active'
      9   group by s.user_id
    10       , s.name
    11       , s.last_name
    12  /
       USER_ID NAME      FULL_NAME            COUNT(WA.WA_ID)
             1 una       una astfirst                       2
             3 pangatlo  pangatlo lastthird                 2
    2 rijen zijn geselecteerd.Regards,
    Rob.

Maybe you are looking for