2017-02-06 3 views
2

Group count and Pivot Queryグループカウントとピボットクエリ

DocBooksが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 
+0

おそらくあなたが共有できるものを試しましたか? –

答えて

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; 

また、ファンシーになりたい場合(co ncise?):

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; 
+0

多くの感謝はそれを行く:)を与えるでしょう – Rosebud

+0

感謝は素晴らしい作品! – Rosebud

2

カウント(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 
+0

多くの感謝はそれに行くだろう:) – Rosebud

+0

@ローズバッドゴードンの答えを見て...私はあなたの質問を過度に単純化している可能性があります –

0

申し訳ありませんが、テーブル名の前に#はありますか?まったく何もしないようです。私はそれを削除したとき、すべてのソリューションは私のために働いた。ちょっと興味があるんだけど。

関連する問題