繁体   English   中英

计算SQL中多个表中的记录

[英]Count records from multiple tables in 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行,而输出应仅是包含所有状态计数的一行。

你近了 case需要是参数的聚合函数,你不想statusid的在group 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 

您可以使用以下所示的数据透视表:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM