我只是想知道是否有办法从一个表中使用一个查询获得两个单独的“计数”总计?也就是说,使用类似于下面的表我想检索每个代码(不同)并显示状态总数'不等于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
我已经看过做子查询等但我似乎无法得到我需要的结果。
有什么想法吗?
感谢。
答案 0 :(得分:53)
<击> 撞击>
<击>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