Rabu, 30 April 2014

Multiple Count Statements With Different Criteria

Table:
Code:  Status  Cancel_Date
-----------------------------------
AAA    X       2012-02-01
AAA
BBB    X       2012-02-01
AAA    D       2012-01-01
AAA
BBB    
BBB    D       2012-02-01
BBB    X       2012-01-01
Example result (based on the above data):
Code:  TotalNotXorD     TotalXorD
------------------------------------
AAA    2                1
BBB    1                2
in SQL SERVER

SELECT  Code,
        SUM(CASE WHEN status NOT IN ('X','D') OR status IS NULL THEN 1 ELSE 0 END) TotalNotXorD,
        SUM(CASE WHEN status IN ('X','D') AND cancel_date >= '2012-02-01' THEN 1 ELSE 0 END) TotalXorD  
FROM    tableName
GROUP   BY Code
in MS ACCESS

 SELECT
    Sum(IIf(status<>'X' and status<>'D',1,0)) AS TotalNotXorD,
    Sum(IIf(status='X' and status='D',1,0)) AS TotalXorD
FROM tableName
GROUP   BY Code



Foto Propades