ID CAT1 CAT2 CAT3 DATE 1 IT NETW cisco1 2015-11-26 2 IT NETW cisco2 2015-11-26 1 IT NETW cisco1 2015-11-27 2 IT NETW cisco2 2015-11-27 3 OT VID dist1 2015-11-26 4 OT VID dist2 2015-11-26 3 OT VID dist1 2015-11-27 4 OT VID dist2 2015-11-27 5 ET ALT flip1 2015-11-26 6 ET ALT flip2 2015-11-26 5 ET ALT flip1 2015-11-27 6 ET ALT flip2 2015-11-27 ecc..
我需要像这样的计数输出:
CAT1 CAT2 CAT3 COUNT(2015-11-26) COUNT(2015-11-27) IT NETW cisco1 1 1 IT NETW cisco2 1 1 OT VID dist1 1 1 OT VID dist1 1 1 ET ALT flip1 1 1 ET ALT flip1 1 1
你可以看到他们被复制了不同的日期。 但是同一时间2015-11-27的日期与2015-11-26相同,并且在这种情况下,计数应输出0或null。你能帮我做一个查询吗?我使用的是SQL Server 2008.
答案 0 :(得分:2)
做GROUP BY
。使用CASE
表达式进行条件计数:
select CAT1, CAT2, CAT3,
count(case when DATE = '2015-11-26' then 1 end) as cnt_2015-11-26,
count(case when DATE = '2015-11-27' then 1 end) as cnt_2015-11-27
from tablename
group by CAT1, CAT2, CAT3
修改强>:
使用派生表计算cnt_2015-11-26和cnt_2015-11-27之间的差异:
select CAT1, CAT2, CAT3, cnt_2015-11-26, cnt_2015-11-27,
cnt_2015-11-26 - cnt_2015-11-27 as difference
from
(
select CAT1, CAT2, CAT3,
count(case when DATE = '2015-11-26' then 1 end) as cnt_2015-11-26,
count(case when DATE = '2015-11-27' then 1 end) as cnt_2015-11-27
from tablename
group by CAT1, CAT2, CAT3
) dt
答案 1 :(得分:2)
使用Cross Apply和Pivot我们也可以做到
select id,
CAT1,
CAT2,
CAT3,
[2015-11-26] AS 'COUNT[2015-11-26]',
[2015-11-27] AS 'COUNT[2015-11-27]' from (
select id,CAT1,CAT2,CAT3,col,val from @t
CROSS APPLY (values('2015-11-26',date),('2015-11-27',date))cs(col,val))T
PIVOT(count(val) FOR COL IN ([2015-11-26],[2015-11-27]))P