2017-08-09 58 views
0

我想從數據庫表中計算文檔的不同狀態。從SQL中的多個表中計數記錄

假設表中的一個具有:

select docid, year, type, statusid 
from table1 
where docid in (1, 2) and year = '2016' 

這將返回:

docid year type statusid 
------------------------ 
1  2016 pdf 231 
1  2016 pdf 231 
1  2016 pdf 231 
1  2016 pdf 232 
1  2016 pdf 232 
1  2016 pdf 235 
1  2016 pdf 235 

,但我需要回到只有一個記錄像

docid year type granted revoked deleted others 
---------------------------------------------------- 
1  2016 pdf 3  2  2  0 

而狀態在不同的表

表2

statusid  status  masterid 
---------------------------------- 
231   granted  51 
232   revoked  51 
235   deleted  51 
236   others  51 

我想的是:

select 
    docid, year, type,statusid 
    case 
     when statusid = 231 
      then count(statusid) 
     else 0 
    as granted, 
    case 
     when statusid = 232 
      then count(statusid) 
     else 0 as revoked, 
    case 
     when statusid = 235 
      then count(statusid) 
     else 0 as deleted, 
    case 
     when statusid = 236 
      then count(statusid) 
     else 0 as others 
from 
    table1 
where 
    docid in (1, 2) and year = '2016' 
group by 
    docid, year, type, statusid 

但這回3行而輸出應該是唯一一個所有狀態數列。

回答

3

你就近了。該case需要在參數的聚合函數,你不想statusidgroup by

select docid, year, type, 
     sum(case when statusid = 231 then 1 else 0 end) as granted, 
     sum(case when statusid = 232 then 1 else 0 end) as revoked, 
     sum(case when statusid = 235 then 1 else 0 end) as deleted, 
     sum(case when statusid = 236 then 1 else 0 end) as others 
from table1 
where docid in (1,2) and year='2016' 
group by docid, year, type 
+0

我試圖從groupby中刪除statusid,但它不允許我使用statusid以防萬一,我不知道sql是如何允許選擇同一列的ggregate案件。謝謝:) – Sandy

1

可以使用旋轉爲同一如下:如下

Select * from (
    Select docid, [year], [type], [status] from table1 d 
    Join table2 dt on d.statusid = dt.statusid 
) a 
Pivot (count([status]) for [status] in ([granted],[revoked],[deleted],[others])) p 

輸出:

+-------+------+------+---------+---------+---------+--------+ 
| docid | year | type | granted | revoked | deleted | others | 
+-------+------+------+---------+---------+---------+--------+ 
|  1 | 2016 | pdf |  3 |  2 |  2 |  0 | 
+-------+------+------+---------+---------+---------+--------+ 
相關問題