sql—如何透视查询中提到的select结果

xhv8bpkk  于 2021-07-26  发布在  Java
关注(0)|答案(3)|浏览(300)

我有如下疑问

SELECT Project
    ,STATUS
    ,count(*) AS [count]
FROM Defect
GROUP BY Project
    ,STATUS
ORDER BY Project

它将返回一张像

我试着把这个结果放在下面

c7rzv4ha

c7rzv4ha1#

你可以试试下面的方法-

SELECT * FROM   
(
    SELECT Project,STATUS,count(*) AS cnt FROM Defect GROUP BY Project,STATUS
) t 
PIVOT(
    sum(cnt) 
    FOR STATUS IN (
        [Build Assigned], 
        [Build Delivered], 
        [Closed], 
        [Eng. Build Delivered], 
        [New], 
        [Non-Issue], 
        [Open],[Pending])
) AS pivot_table
e4yzc0pl

e4yzc0pl2#

会是

with base as
(
SELECT Project
    ,STATUS
    ,count(*) AS [count]
FROM Defect
GROUP BY Project
    ,STATUS
)
select *
from base
pivot (
sum([count])
for base.status in ([Build Delivered],[New],[...],[...])
) as x
order by project
;
9bfwbjaz

9bfwbjaz3#

可以使用聚合函数 sumcase 表达式如下

select
  project,
  sum(case when status = 'Build Assigned' then count else 0 end) as Build_Assigned,
  sum(case when status = 'Build Delivered' then count else 0 end) as Build_Delivered
from yourTable
group by
  project

相关问题