我需要帮助SQL来生成包含行/列总计的数据透视表。我有2个表,如下所示
Table ProbCat
==============
probcat | probdesc
1 minor
2 high
3 showstopper
Table ProbSummary
===================
prodcat | noofproblems | stage
1 5 Dev
2 1 Dev
3 6 QA
3 6 Prod
我想生成一个包含行/列总百分比的数据透视表,如下所示。我尝试过'pivot'和'group by'的组合,但无法获得行和&列总计准确
ProbCategory CategoryDesc Dev Qa Prod Total(%)
______________________________________________________
1 Minor 5 0 0 5(100*(5/18))
2 High 1 0 0 1(100*(1/18))
3 Showstopper 0 6 6 12(100*(6/18))
Total NA 6(%) 6(%) 6(%)
答案 0 :(得分:0)
with x as
(select p.probcat as probcategory, p.probdesc as categotydesc,
case when s.stage = 'Dev' and s.noofproblems > 0 then s.noofproblems else 0 end as Dev,
case when s.stage = 'QA' and s.noofproblems > 0 then s.noofproblems else 0 end as QA,
case when s.stage = 'Prod' and s.noofproblems > 0 then s.noofproblems else 0 end as Prod
from Probcat p join Probsummary s on p.probcat = s.prodcat)
select probcategory,categotydesc,Dev,QA,Prod, Dev+QA+Prod as Total
from x
除了底部的Total
行外,这应该是你需要的。
答案 1 :(得分:0)
就像其他提到的那样,您的摘要/总计算应该在表示层上完成。但这是我尝试将您的输出减去最后一个摘要行:
;WITH Q1
AS (
SELECT pvt.probcat
,pvt.probdesc
,ISNULL(pvt.[Dev], 0) AS 'Dev'
,ISNULL(pvt.[QA], 0) AS 'QA'
,ISNULL(pvt.[Prod], 0) AS 'Prod'
FROM (
SELECT pc.probcat
,pc.probdesc
,ps.noofproblems
,ps.stage
FROM Probcat pc
LEFT JOIN ProbSummary ps ON pc.probcat = ps.probcat
) t
PIVOT(max(noofproblems) FOR stage IN (
[Dev]
,[QA]
,[Prod]
)) pvt
),
q2 as
(SELECT q1.*
,sum(q1.Dev + q1.QA + q1.Prod) AS Total
FROM q1
GROUP BY q1.probcat
,q1.probdesc
,q1.Dev
,q1.QA
,q1.Prod
)
select q2.probcat
,q2.probdesc
,q2.Dev
,q2.QA
,q2.Prod
,cast(q2.Total as varchar(10)) + ' (' +
cast(cast((cast(q2.Total as decimal(5,2))/cast(d.CrossSum as decimal(5,2)))*100
as decimal(5,2)) as varchar(10))
+ '% )' as FinalTotal
from q2
CROSS APPLY (
SELECT sum(q1.Dev + q1.QA + q1.Prod) AS CrossSum
FROM q1
) d
ORDER BY q2.probcat