如果文档包含 A 和 B,则将计数添加到 DocCompleted。如果只有 A 或 B 或 Null,则将计数添加到未完成中。
create table #TempRecords
(
EmpId int not null,
Doc_Name nvarchar(50),
DateCreated datetime ,
)
insert into #TempRecords values
(1001,'Doc_A','2016-10-15 07:57:37'),
(1001,'Doc_B','2016-10-15 07:57:37'),
(1001,'Doc_A','2016-10-15 07:57:37'),
(1001,'Doc_A','2016-10-15 07:57:37'),
(2001,'Doc_A','2016-10-15 07:57:37'),
(2001,'Doc_B','2016-10-15 07:57:37'),
(2001,'Doc_A','2016-10-15 07:57:37'),
(2001,'Doc_A','2016-10-15 07:57:37'),
(3001,null,null),
(3001,'Doc_A','2016-10-15 14:57:37'),
(3004,null,null)
select * from #TempRecords
最佳答案
您可以通过两个级别的聚合来完成此操作:
select count(*) as EmpCount,
sum(case when num_a > 0 and num_b > 0 then 1 else 0 end) as DocCompletedCount,
sum(case when num_a = 0 or num_b = 0 then 1 else 0 end) as DocUnCompletedCount
from (select empid,
sum(case when doc_name = 'Doc_A' then 1 else 0 end) as num_a,
sum(case when doc_name = 'Doc_B' then 1 else 0 end) as num_b
from #temprecords
group by empid
) t;
或者,如果你想变得花哨(简洁?):
select count(*) as EmpCount,
sum(has_a * has_b),
sum(1 - has_a * has_b) as DocUnCompletedCount
from (select empid,
max(case when doc_name = 'Doc_A' then 1 else 0 end) as has_a,
max(case when doc_name = 'Doc_B' then 1 else 0 end) as has_b
from #temprecords
group by empid
) t;
关于sql - 组计数和透视查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42077982/