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行而输出应该是唯一一个所有状态数列。
我试图从groupby中删除statusid,但它不允许我使用statusid以防万一,我不知道sql是如何允许选择同一列的ggregate案件。谢谢:) – Sandy