SQL query using Group by and Aggregate function

Hi All,
I need your help in writing an SQL query to achieve the following.
Scenario:
I have table with 3 Columns. There are 3 possible values for col3 - Success, Failure & Error.
Now I need a query which can give me the summary counts for distinct values of col3 for each GROUP BY of col1 and col2 values. When there are no values for col3 then it should return ZERO count.
Example Data:
Col1 Col2 Col3
abc 01 success
abc 02 success
abc 01 success
abc 01 Failure
abc 01 Error
abc 02 Failure
abc 03 Error
xyz 07 Failure
Required Output:
c1 c2 s_cnt F_cnt E_cnt (Heading)
abc 01 2 1 1
abc 02 1 1 0
abc 03 0 0 1
xyz 07 0 1 0
s_cnt = Success count; F_cnt = Failure count; E_cnt = Error count
Please note that the output should have 5 columns with col1, col2, group by (col1,col2)count(success), group by (col1,col2)count(failure), group by (col1,col2)count(error)
and where ever there are NO ROWS then it should return ZERO.
Thanks in advance.
Regards,
Shiva

Hi,
user13015050 wrote:
Thanks TTT. Unfortunately I cannot use this solution because I have huge data for this.T's solution is basically the same as mine. The first 23 lines just simulates your table. Since you actually have a table, you would start with T's line 24:
SELECT col1 c1, col2 c2, SUM(decode(col3, 'success', 1, 0)) s_cnt, ...
user13015050 wrote:Thanks a lot Frank. It helped me out. I just did some changes to this as below and have no issues.
SELECT     col1
,     col2
,     COUNT ( CASE
          WHEN col3 = 'SUCCESS'
          THEN 1
          END
     )          AS s_cnt
,     COUNT ( CASE
          WHEN col3 = 'FAILED'
          THEN 1
          END
     )          AS f_cnt
,     COUNT ( CASE
          WHEN col3 = 'ERROR'
          THEN 1
          END
     )          AS e_cnt
FROM     t1
WHERE c2 in ('PURCHASE','REFUND')
and c4 between to_date('20091031000000','YYYYMMDDHH24MISS') AND to_date('20100131235959','YYYYMMDDHH24MISS')
GROUP BY c1, c2
ORDER BY c1, c2;
Please let me know if you see any issues in this query.It's very hard to read.
This site normally compresses spaces. Whenever you post formatted text (such as queries or results) on this site, type these 6 characters:
\(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.
Also, post exactly what you're using.  The code above is SELECTing col1 and col2, but there's no mention of either in the GROUP BY clause, so I don't believe it's really what you're using.
Other than that, I don't see anything wrong or suspicious in the query.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Similar Messages

  • Sqlserver query using Group by and Order by

    SUM(BILL_DETAIL.x_bill_quantity) as BILL_QUANTITY,
    MIN(BILL_DETAIL.x_billable_to) as BILLABLE_TO,
    MIN(BILL_DETAIL.x_billable_yn) as BILLABLE_YN,
    AVG(BILL_DETAIL.x_bill_rate) as BILL_RATE,
    MIN(BILL_DETAIL.x_cost_rate) as COST_RATE,
    MIN(BILL_DETAIL.x_cost_total) as COST_TYPE,
    LISTAGG(BILL_DETAIL.objid, ',') WITHIN GROUP(ORDER BY BILL_DETAIL.objid) as ID_LIST
    FROM table_x_gsa_bill_detail BILL_DETAIL
    WHERE (1=1)
    GROUP BY (DECODE(BILLABLE_YN, 1, 'Billable', 'Non-Billable') || ',' || BILLABLE_TO || ',' || DETAIL_CLASS || ',' || COST_TYPE || ',' || BILL_RATE)
    ORDER BY DECODE(BILLABLE_YN, 1, 'Billable', 'Non-Billable') || ',' || BILLABLE_TO || ',' || DETAIL_CLASS ||
    ) dt WHERE rn BETWEEN 0 AND 1
    Can any one pls help me using of Case Condition keyword instead of Decode in the above query ??? iam not able to convert above query for group by and order by..
    Actually i need to do group by the aggragate values which i got the values from the fields of BILLABLE_YN,BILLABLE_TO,DETAIL_CLASS, COST_TYPE, BILL_RATE.
    where as in oracle i can run above query using decode keyword where as in sqlserver iam not able to use BILLABLE_YN field alias of above query in group by .
    i tried like by using following way but it is wrong because here iam not using aggragate values of fields in group by funtion please help me in converting query in sqlserver. GROUP BY (case BILLABLE_YN when 1 then 'Billable' when 0 then 'Non-Billable' else
    'Non-Billable' End BILLABLE_YN + ',' + BILLABLE_TO + ',' + DETAIL_CLASS + ',' + COST_TYPE + ',' + BILL_RATE)
    Krishna

    CREATE TABLE DETAIL
    ([objid] int,[x_billable_to] varchar(19), [x_bill_quantity] int,
    [x_billable_yn] int, [x_bill_rate] int, [COST_TYPE] varchar(19) )
    INSERT INTO
    DETAIL
    ([objid], [x_billable_to], [x_bill_quantity], [x_billable_yn], [x_bill_rate],[COST_TYPE])
    VALUES
    (1, 'Customer', 3, 1, 20,'Parking'),
    (2, 'Customer', 1, 1, 25,'Toll'),
    (3, 'Customer', 2, 1, 20,'Parking') 
    Pls convert following query for executing query in sqlserver  ..for the column ID_List it should return data like 1,2,3
    SELECT * FROM (SELECT 1 rn,
            SUM(BILL_DETAIL.x_bill_quantity)      as BILL_QUANTITY,
            MIN(BILL_DETAIL.x_billable_to)        as BILLABLE_TO,
            MIN(BILL_DETAIL.x_billable_yn)        as BILLABLE_YN,
            AVG(BILL_DETAIL.x_bill_rate)          as BILL_RATE,
            LISTAGG(BILL_DETAIL.objid, ',') WITHIN GROUP(ORDER BY BILL_DETAIL.objid) as ID_LIST
         FROM   BILL_DETAIL
          WHERE (1=1)
     GROUP BY (DECODE(x_billable_yn, 1, 'Billable', 'Non-Billable') + ',' + x_billable_to  +  ',' + COST_TYPE + ',' + x_bill_rate)
          ORDER BY DECODE(x_billable_yn, 1, 'Billable', 'Non-Billable') + ',' + x_billable_to  +  ',' + COST_TYPE + ',' + x_bill_rate
           )dt 
    WHERE rn BETWEEN 0 AND 1
    Krishna
    sounds like this
    SELECT *
    FROM
    SELECT 1 rn,
    SUM(BILL_DETAIL.x_bill_quantity) as BILL_QUANTITY,
    MIN(BILL_DETAIL.x_billable_to) as BILLABLE_TO,
    MIN(BILL_DETAIL.x_billable_yn) as BILLABLE_YN,
    AVG(BILL_DETAIL.x_bill_rate) as BILL_RATE,
    LEFT(bd1.ID_LIST,LEN(bd1.ID_LIST)-1) AS ID_Listing
    FROM BILL_DETAIL bd
    CROSS APPLY (
    SELECT BILL_DETAIL.objid + ',' AS [text()]
    FROM BILL_DETAIL
    WHERE objid = bd.objid
    FOR XML PATH('')
    )bd1(ID_LIST)
    WHERE (1=1)
    GROUP BY (CASE WHEN x_billable_yn = 1 THEN 'Billable' ELSE 'Non-Billable'END + ',' + x_billable_to + ',' + COST_TYPE + ',' + x_bill_rate),
    LEFT(bd1.ID_LIST,LEN(bd1.ID_LIST)-1)
    ORDER BY (CASE WHEN x_billable_yn = 1 THEN 'Billable' ELSE 'Non-Billable'END + ',' + x_billable_to + ',' + COST_TYPE + ',' + x_bill_rate),
    LEFT(bd1.ID_LIST,LEN(bd1.ID_LIST)-1)
    )dt
    WHERE rn BETWEEN 0 AND 1
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • Any difference between distinct and aggregate function in sql query cost???

    Hi,
    I have executed many sql stmts patterns- such as:
    a) using a single table
    b) using two tables, using simple joins or outer joins
    but i have not noticed any difference in sql stmts in cost and in execution plan....
    Anyway, my colleague insists on that using aggregate function is less costly compared to
    distinct....(something i have not confirmed, that's why i beleive that they are exactly the same...)
    For the above reffered 1st sql pattern.. we could for example use
    select distinct deptno
    from emp
    select count(*), deptno
    from emp
    group by deptno select distinct owner, object_type from all_objects
    select count(*), owner, object_type from all_objects
    group by owner, object_typeHave you found any difference between the two ever...????
    Note: I use Ora DB 10g v2.
    Thank you,
    Sim

    distinct and aggregate function are for different uses and may give same result but if u r using aggregate function to get distinct records, it will be expensive...
    ex
    select distinct deptno from scott.dept;
    Statistics
    0 recursive calls
    0 db block gets
    2 consistent gets
    0 physical reads
    0 redo size
    584 bytes sent via SQL*Net to client
    488 bytes received via SQL*Net from client
    2 SQL*Net roundtrips to/from client
    0 sorts (memory)
    0 sorts (disk)
    4 rows processed
    select deptno from scott.emp group by deptno;
    Statistics
    307 recursive calls
    0 db block gets
    60 consistent gets
    6 physical reads
    0 redo size
    576 bytes sent via SQL*Net to client
    488 bytes received via SQL*Net from client
    2 SQL*Net roundtrips to/from client
    6 sorts (memory)
    0 sorts (disk)
    3 rows processed
    Nimish Garg
    Software Developer
    *(Oracle & ASP.NET)*
    Indiamart Intermesh Limited, Noida
    To Get Free Oracle & ASP.NET Code Snippets
    Follow: http://nimishgarg.blogspot.com

  • Need complex query  with joins and AGGREGATE  functions.

    Hello Everyone ;
    Good Morning to all ;
    I have 3 tables with 2 lakhs record. I need to check query performance.. How CBO rewrites my query in materialized view ?
    I want to make complex join with AGGREGATE FUNCTION.
    my table details
    SQL> select from tab;*
    TNAME TABTYPE CLUSTERID
    DEPT TABLE
    PAYROLL TABLE
    EMP TABLE
    SQL> desc emp
    Name
    EID
    ENAME
    EDOB
    EGENDER
    EQUAL
    EGRADUATION
    EDESIGNATION
    ELEVEL
    EDOMAIN_ID
    EMOB_NO
    SQL> desc dept
    Name
    EID
    DNAME
    DMANAGER
    DCONTACT_NO
    DPROJ_NAME
    SQL> desc payroll
    Name
    EID
    PF_NO
    SAL_ACC_NO
    SALARY
    BONUS
    I want to make  complex query  with joins and AGGREGATE  functions.
    Dept names are : IT , ITES , Accounts , Mgmt , Hr
    GRADUATIONS are : Engineering , Arts , Accounts , business_applications
    I want to select records who are working in IT and ITES and graduation should be "Engineering"
    salary > 20000 and < = 22800 and bonus > 1000 and <= 1999 with count for males and females Separately ;
    Please help me to make a such complex query with joins ..
    Thanks in advance ..
    Edited by: 969352 on May 25, 2013 11:34 AM

    969352 wrote:
    why do you avoid providing requested & NEEDED details?I do NOT understand what do you expect ?
    My Goal is :
    1. When executing my own query i need to check expalin plan.please proceed to do so
    http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_9010.htm#SQLRF01601
    2. IF i enable query rewrite option .. i want to check explain plan ( how optimizer rewrites my query ) ? please proceed to do so
    http://docs.oracle.com/cd/E11882_01/server.112/e16638/ex_plan.htm#PFGRF009
    3. My only aim is QUERY PERFORMANCE with QUERY REWRITE clause in materialized view.It is an admirable goal.
    Best Wishes on your quest for performance improvements.

  • Analytic function and aggregate function

    What are analytic function and aggregate function. What is difference between them?

    hi,
    Analytic Functions :----------
    Analytic functions compute an aggregate value based on a group of rows. They differ from aggregate functions in that they return multiple rows for each group. The group of rows is called a window and is defined by the analytic_clause. For each row, a sliding window of rows is defined. The window determines the range of rows used to perform the calculations for the current row. Window sizes can be based on either a physical number of rows or a logical interval such as time.
    Analytic functions are the last set of operations performed in a query except for the final ORDER BY clause. All joins and all WHERE, GROUP BY, and HAVING clauses are completed before the analytic functions are processed. Therefore, analytic functions can appear only in the select list or ORDER BY clause.
    Analytic functions are commonly used to compute cumulative, moving, centered, and reporting aggregates.
    Aggregate Functions :----------
    Aggregate functions return a single result row based on groups of rows, rather than on single rows. Aggregate functions can appear in select lists and in ORDER BY and HAVING clauses. They are commonly used with the GROUP BY clause in a SELECT statement, where Oracle Database divides the rows of a queried table or view into groups. In a query containing a GROUP BY clause, the elements of the select list can be aggregate functions, GROUP BY expressions, constants, or expressions involving one of these. Oracle applies the aggregate functions to each group of rows and returns a single result row for each group.
    If you omit the GROUP BY clause, then Oracle applies aggregate functions in the select list to all the rows in the queried table or view. You use aggregate functions in the HAVING clause to eliminate groups from the output based on the results of the aggregate functions, rather than on the values of the individual rows of the queried table or view.
    let me know if you are feeling any problem in understanding.
    thanks.
    Edited by: varun4dba on Jan 27, 2011 3:32 PM

  • Need to run a sql query in the background and display the output in HTML

    Hi Guys,
    I have a link in my iprocurement webpage, when i click this link, a query (sql query) should be run and the output should be displayed in a HTML page. Any ideas of how this can be done. Help appreciated.
    We dont have OA Framework and we r using 11.5.7.
    help needed
    thanx

    Read Metalink Note 275880.1 which has the link to developer guide and personalization guide.

  • How to obtain the transformed SQL query using SEM_MATCH

    Dear all,
    Is it possible to get the transformed relational SQL query when using the SEM_MATCH prefix, by querying directly on the database. We are able to obtain the relational SQL query using Joseki/Jena, however this is not the way to go for us. We would like (if possible) to get it straight from the oracle database by logging or something.
    Kind regards.
    Max

    Hi Max,
    Just to clarify. What SEM_MATCH prefix are you talking about?
    A SEM_MATCH based query is indeed a SQL query as SEM_MATCH is a SQL table function. So if you don't want to go through Java APIs or web service endpoint, then running SEM_MATCH directly should give you what you need. Or maybe you just want to see the underlying generated (from SEM_MATCH) SQL query. If that is true, can you please tell us why?
    Thanks,
    Zhe Wu

  • Set TIMEOUT on OCCI sql query using ?

    Is there a way to set a timeout on a sql query using OCCI ?

    OCCI does not provide an API to set timeouts on SQL Queries.
    You can use the CREATE PROFILE command and assign resources at
    a user level. The restrictions may be applied to memory/resources which
    in turn would control the SQL execution time. Please check the
    CREATE PROFILE command.
    Rgds
    Amogh

  • In the numbers app, using the "date and time" function, is it possible to remove the time? I need to put together a list of dates, but I don't need or want times.

    In the numbers app, using the "date and time" function, is it possible to remove the time? I need to put together a list of dates, but I don't need or want times.

    When formatting your column to date/time, pick Date & time, and then pick the letter i in the circle to the right. Then scroll down and pick "No time"
    Jason

  • What is the difference using start condition and check function module

    what is the difference  between using start condition and check function module

    That's new to me, I thought a start condition was evaluated before the workflow started, and thus now workflow work item is available. That's why I think the only situation in which start conditions/check functions can't be used, is when the availability of a workflow log for investigation of exactly what stopped the workflow is a requirement.
    I suppose the <a href="http://help.sap.com/saphelp_46c/helpdata/en/4c/86bf43feca11d2a64f0060087a79ea/frameset.htm">SAP documentation</a> is in need of an update.

  • How to find sql query using sqlid

    Hi
    I am not aware of that sqlid .DBA is saying a particular sqlid is making problem .how to find the particular sql query using sql_id ?

    Are you aware of modplsql when i executed the query the result is like
    DECLARE
       rc__             NUMBER;
       simple_list__    OWA_UTIL.vc_arr;
       complex_list__   OWA_UTIL.vc_arr;
    BEGIN
       OWA.init_cgi_env (:n__, :nm__, :v__);
       HTP.htbuf_len := 84;
       NULL;
       NULL;
       simple_list__ (1) := 'sys.%';
       simple_list__ (2) := 'dbms\_%';
       simple_list__ (3) := 'utl\_%';
       simple_list__ (4) := 'owa\_%';
       simple_list__ (5) := 'owa.%';
       simple_list__ (6) := 'htp.%';
       simple_list__ (7) := 'htf.%';
       simple_list__ (8) := 'wpg_docload.%';
       IF ((owa_match.match_pattern ('Oly_browse.oly_pattern ',
                                     simple_list__,
                                     complex_list__,
                                     TRUE
       THEN
          rc__ := 2;
       ELSE
          NULL;
          NULL;
         oly_browse.oly_pattern (search_phrase      => :search_phrase,           --Oly_browse.oly_pattern is package name
                                btn                => :btn,
                                p_qual             => :p_qual,
                                p_bcat             => :p_bcat,
                                p_stdy             => :p_stdy,
                                p_bloc             => :p_bloc,
                                z                  => :z
          IF (WPG_DOCLOAD.is_file_download)
          THEN
             rc__ := 1;
             WPG_DOCLOAD.get_download_file (:doc_info);
             NULL;
             NULL;
             NULL;
             COMMIT;
          ELSE
             rc__ := 0;
             NULL;
             NULL;
             NULL;
             COMMIT;
             OWA.get_page (:data__, :ndata__);
          END IF;
       END IF;
       :rc__ := rc__;
    END; Edited by: vishnu prakash on Sep 8, 2010 10:16 PM

  • Firefox does not open with the tabs I had open when I use the quit and save function. Firefox opens with my home page only. how to fix?

    When I use the "Save and Quit" function it has no effect. The next time I open Firefox it goes to my home page only.
    == This happened ==
    Every time Firefox opened
    == 3 days ago

    This is not a solution, nor a work-around. The only thing this points out is where the problem lies. Settings are meant to be used in all sessions, barring exceptions and the fact that Firefox asks if you'd rather SAVE and then quit, makes it an exception. The user has elected to skip the clear browsing history step.
    However, if the settings are permanently changed as you suggest, then the history will always be remembered for eternity when Firefox is closed. You then have to manually clear your history first at every session before closing.
    Older versions of Firefox never behaved in such manner and recognized that the Save and Quit superseded the setting to Clear History.

  • How can I deploy EFS using Group Policy and automatically encrypt computers for ALL users who login?

    How can I deploy EFS using Group Policy and Active Directory with a goal to automatically encrypt computers for ALL users who login? (NOT an option for me to use BitLocker)
    I was asked to deploy EFS to encrypt the user my documents folder and profile on all of the users laptops. The laptops are in common areas (board meeting rooms, etc) and security of files is a must.
    I successfully created a recovery certificate in AD. I created an OU and setup an EFS policy and users can now login and select to encrypt their own files. The issue is that management would like to have automaticy Encrypt ALL users my documents AUTOMATICALLY
    when a user login.
    Can this be done?
    Please help

    Hi,
    Any update?
    Just checking in to see if the suggestions were helpful. Please let us know if you would like further assistance.
    Best Regards,
    Andy Qi
    TechNet Subscriber Support
    If you are
    TechNet Subscription user and have any feedback on our support quality, please send your feedback
    here.
    Andy Qi
    TechNet Community Support

  • Using a SQL Query in an Alert and Matching a String

    I've created an alert in 12.0.4 using a SQL Query and the field that I'm trying to match is a string.  Originally the query returned multiple rows but when the alert still didn't fire, I modified the query WHERE clause to return only one row:
    NAME                                RESPONSE
    Are area lights working?            No
    My expression in the metric is RESPONSE.  In the Monitor I'm matching a string equal to No.  (Do I need double quotes around the matchvalue?  Single quotes?  No quotes?)  The metric is in the 15min scan group, the role is xMII Developers and I'm in that role. The monitor alert string is ' =  '.  Both metric and monitor are active and I've subscribed to the monitor.  Other alerts in the 15min scan group (all based on tag queries) are firing off properly.
    Why is nothing showing up in the Alert Log?
    David Macindoe

    David,
    Did you figure out the answer?  If not, I will try to find someone to address your question.
    Mike

  • Error in SQL Query The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator. for the query

    hi Experts,
    while running SQL Query i am getting an error as
    The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator. for the query
    select  T1. Dscription,T1.docEntry,T1.Quantity,T1.Price ,
    T2.LineText
    from OQUT T0  INNER JOIN QUT1 T1 ON T0.DocEntry = T1.DocEntry INNER JOIN
    QUT10 T2 ON T1.DocEntry = T2.DocEntry where T1.DocEntry='590'
    group by  T1. Dscription,T1.docEntry,T1.Quantity,T1.Price
    ,T2.LineText
    how to resolve the issue

    Dear Meghanath,
    Please use the following query, Hope your purpose will serve.
    select  T1. Dscription,T1.docEntry,T1.Quantity,T1.Price ,
    CAST(T2.LineText as nvarchar (MAX))[LineText]
    from OQUT T0  INNER JOIN QUT1 T1 ON T0.DocEntry = T1.DocEntry LEFT OUTER JOIN
    QUT10 T2 ON T1.DocEntry = T2.DocEntry --where T1.DocEntry='590'
    group by  T1. Dscription,T1.docEntry,T1.Quantity,T1.Price
    ,CAST(T2.LineText as nvarchar (MAX))
    Regards,
    Amit

Maybe you are looking for

  • After upgrading to Mavericks, iPhoto does not work

    I have an iMac early 2011, with dual hard drives. After upgrading to Mavericks, iPhoto and several other apps are no longer "installed". The following apps have a white circle with a line through it in my main Applications folder on my primary hard d

  • User Uploading documents in Service desk

    Hello, We are in process of configuring SAP service desk at a client site. The client requirement is if the support team requires some information from the user, we send the ticket back to the user with status eg. Request for information (We have don

  • Adobe Photoshop CS6: Photoshop.exe - System Error  The program can't start because ONCoreFoundation7

    I get this error after updating ONONE premium edition 8 to 8.1 been to their site no luck in resoving error. I click ok to error PS cs6 still launches, just annoying. ONCoreFoundation7.dll  is part of ONONE 7

  • ICEfaces + Tomcat and subdirecotry problem

    Hi I have an ICEfaces webapplication. let's call it 'myapp'. I decided to create additional subdirectory called survey. The directory holds some *.iface files When I try to invoke a file via domain name: http://www.mydomain.com/survey/survey1.iface t

  • Java.io.FileNotFoundException: JAR entry META-INF/wsdl/....

    Hi Guys! I am having the following problem with my webdynpro java application on CE 7.1: In one of my dc's i am calling another dc which is an ejb. The called ejb calls a webservice. (my dc --> ejb --> webservice) My dc has nothing to do with the web