列到行

时间:2016-10-07 11:07:06

标签: sql sql-server unpivot

我正在使用SQL 2008数据库 我正在处理一个报告我想在图表中显示我这样做我需要将我的结果从列转换为行 这是我的查询

SELECT 
COUNT(CASE WHEN (pm.mortgagestatus) = 10  then 1 end) AS Received,
SUM(case WHEN (pm.mortgagestatus) = 10 then pm.AmountRequested Else 0 END) AS [Received Amount],
COUNT(CASE WHEN (pm.mortgagestatus) = 4  then 1 end) AS Passed,
SUM(case WHEN (pm.mortgagestatus) = 4 then pm.AmountRequested Else 0 END) AS [Passed Amount],
COUNT(CASE WHEN (pm.mortgagestatus) = 5  then 1 end) AS packaged,
SUM(case WHEN (pm.mortgagestatus) = 5 then pm.AmountRequested Else 0 END) AS [Packaged Amount],
COUNT(CASE WHEN (pm.mortgagestatus) = 6  then 1 end) AS Offered,
SUM(case WHEN (pm.mortgagestatus) = 6 then pm.AmountRequested Else 0 END) AS [Offered Amount]
FROM tbl_Profile AS p
INNER JOIN tbl_Profile_Mortgage AS pm
ON p.id = pm.fk_ProfileID

此查询返回 enter image description here

我希望查询能够像这样返回。

enter image description here

这样我就可以将数据放入图表中。 对此有任何帮助,非常感谢。 干杯

1 个答案:

答案 0 :(得分:3)

将聚合与case

一起使用
SELECT (CASE WHEN pm.mortgagestatus = 10  then 'Received'
             WHEN pm.mortgagestatus = 4  then 'Passed'
             WHEN pm.mortgagestatu) = 5  then 'packaged'
             WHEN pm.mortgagestatus = 6  then 'Offered'
        END) as Mortgage_Status,
       COUNT(*) as Total,
       SUM(pm.AmountRequested) as LoanAmount
FROM tbl_Profile p INNER JOIN
     tbl_Profile_Mortgage pm
     ON p.id = pm.fk_ProfileID
WHERE pm.mortgagestatus IN (4, 5, 6, 10)
GROUP BY (CASE WHEN pm.mortgagestatus = 10  then 'Received'
               WHEN pm.mortgagestatus = 4  then 'Passed'
               WHEN pm.mortgagestatu) = 5  then 'packaged'
               WHEN pm.mortgagestatus = 6  then 'Offered'
          END);