37

我只是想知道是否有任何方法可以使用一个查询从表中获取两个单独的“计数”总数?也就是说,使用类似于以下的表格,我想检索每个代码(不同的)并显示状态总数不等于 X 或 D,然后有一个附加列显示状态总数等于到 X 或 D 并且取消日期大于给定日期(例如,过去 14 天)。

桌子:

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

示例结果(基于上述数据):

Code:  TotalNotXorD     TotalXorD
------------------------------------
AAA    2                1
BBB    1                2

TotalNotXorD:例如

select code, count(*) 
from table 
where status not in('X','D') 
group by code

TotalXorD:例如

select code, count(*) 
from table 
where status in('X','D') 
  and cancel_date >= '2012-02-01' 
group by code

我看过做子查询等,但我似乎无法得到我需要的结果。

有任何想法吗?

谢谢。

4

1 回答 1

91

SELECT  a.code,
        COALESCE(b.totalNotXorD, 0 ) totalNotXorD,
        COALESCE(c.totalXorD, 0 ) totalXorD,
FROM    (SELECT DISTINCT Code FROM tableName) a
        LEFT JOIN
        (
            select code, count(*) totalNotXorD
            from table 
            where status not in('X','D') 
            group by code
        ) b ON a.code = b.code
        LEFT JOIN
        (
            select code, count(*) totalXorD
            from table 
            where status in('X','D') 
              and cancel_date >= '2012-02-01' 
            group by code
        ) c ON a.code = c.code

或者干脆做CASE

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
于 2013-02-06T23:41:40.803 回答