我只是想知道是否有任何方法可以使用一个查询从一个表中获得两个单独的“计数”总数?也就是说,使用类似于以下的表,我想检索每个代码(不同)并显示状态总数“不等于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
我已经看过做子查询等,但似乎无法获得所需的结果。
有任何想法吗?
谢谢。
~~~~
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
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