sql - 组计数和透视查询

标签 sql sql-server

Group count and Pivot Query

如果文档包含 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/

相关文章:

sql - 如何分隔字符串并转换为列标题?

SQL/Postgres : Find Tuple with Same Value (for a Given Value in another column)

sql - SQL Azure 上的查询性能极差

sql-server - key 锁实际上锁定了什么资源?

sql - Microsoft SQL Server Like 关键字

php - 显示 "Subscriber"帖子和用户自己的帖子

php - 当您只进行一次选择时,使用准备好的 Select 语句是否更好?

python - django 的分页在 django View 中是如何工作的

c# - System.Data.Entity.ModelConfiguration.ModelValidationException

SQL Server 在多个字段上进行透视