组计数和数据透视查询

时间:2017-02-06 21:57:35

标签: sql sql-server

Group count and Pivot Query

如果有A和B的文档然后计数添加到DocCompleted。如果只有A或B或Null则将count添加到unCompleted。

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

3 个答案:

答案 0 :(得分:2)

Count(Distinct ...)和条件聚合可以做到这一点

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

答案 1 :(得分: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;

答案 2 :(得分:0)

很抱歉,但桌面名称前面的#是做什么的?好像什么都没做。当我删除它时,所有解决方案都适合我。好奇。