Sql 组计数和数据透视查询

Sql 组计数和数据透视查询,sql,sql-server,Sql,Sql Server,如果文档中有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

如果文档中有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

CountDistinct。。。条件聚合也可以做到这一点

Select EmpCount = count(Distinct EmpID)
      ,DocCompletedCount = count(Distinct Doc_Name)
      ,unCompletedCount = sum(case when Doc_Name is null then 1 else 0 end)
 From  #TempRecords
返回

EmpCount    DocCompletedCount   unCompletedCount
4           2                   2

您可以通过两个级别的聚合来实现这一点:

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;

对不起,但是表名前面的是什么?它似乎什么也没做。当我移除它时,所有的解决方案都对我有效。只是好奇。

也许你试过一些可以分享的东西?@Rosebud看着Gordon的答案。。。我可能把你的问题简化了