Sql Server:如何将行转换为列?

时间:2011-11-09 08:48:47

标签: sql

这可能是一个已经被问到的问题...但我有点难以解决我的问题。 我需要将基于行的查询转置到列。 我解释: 这是我的实际查询结果

Year     Month     Value
2010      Jan         19
2010      Feb         10
...

我需要

Year      Jan        Feb         ...         Dec
2010      19         20          ...         ...
2011      11         ..          ...           

实际上,我的主要查询非常简单..

SELECT     SUM(QTYCALC) AS TOT, YEAR(SCHEDSTART) AS MyYear, MONTH(SCHEDSTART) AS MyMonth
FROM         PRODTABLE
GROUP BY YEAR(SCHEDSTART), MONTH(SCHEDSTART)

提前致谢

1 个答案:

答案 0 :(得分:1)

您需要使用PIVOT来实现这一目标 - 有关解释和一些示例,请参阅http://msdn.microsoft.com/en-us/library/ms177410.aspxhttp://www.simple-talk.com/community/blogs/andras/archive/2007/09/14/37265.aspx

另一种选择是:

SELECT
YEAR(SCHEDSTART) AS MyYear, 
(SELECT SUM(X.QTYCALC) FROM PRODTABLE X WHERE MONTH(X.SCHEDSTART) = 1 AND YEAR(X.SCHEDSTART) = YEAR(P.SCHEDSTART)) AS Jan,
(SELECT SUM(X.QTYCALC) FROM PRODTABLE X WHERE MONTH(X.SCHEDSTART) = 2 AND YEAR(X.SCHEDSTART) = YEAR(P.SCHEDSTART)) AS Feb,
(SELECT SUM(X.QTYCALC) FROM PRODTABLE X WHERE MONTH(X.SCHEDSTART) = 3 AND YEAR(X.SCHEDSTART) = YEAR(P.SCHEDSTART)) AS Mar,
(SELECT SUM(X.QTYCALC) FROM PRODTABLE X WHERE MONTH(X.SCHEDSTART) = 4 AND YEAR(X.SCHEDSTART) = YEAR(P.SCHEDSTART)) AS Apr,
(SELECT SUM(X.QTYCALC) FROM PRODTABLE X WHERE MONTH(X.SCHEDSTART) = 5 AND YEAR(X.SCHEDSTART) = YEAR(P.SCHEDSTART)) AS May,
(SELECT SUM(X.QTYCALC) FROM PRODTABLE X WHERE MONTH(X.SCHEDSTART) = 6 AND YEAR(X.SCHEDSTART) = YEAR(P.SCHEDSTART)) AS Jun,
(SELECT SUM(X.QTYCALC) FROM PRODTABLE X WHERE MONTH(X.SCHEDSTART) = 7 AND YEAR(X.SCHEDSTART) = YEAR(P.SCHEDSTART)) AS Jul,
(SELECT SUM(X.QTYCALC) FROM PRODTABLE X WHERE MONTH(X.SCHEDSTART) = 8 AND YEAR(X.SCHEDSTART) = YEAR(P.SCHEDSTART)) AS Aug,
(SELECT SUM(X.QTYCALC) FROM PRODTABLE X WHERE MONTH(X.SCHEDSTART) = 9 AND YEAR(X.SCHEDSTART) = YEAR(P.SCHEDSTART)) AS Sep,
(SELECT SUM(X.QTYCALC) FROM PRODTABLE X WHERE MONTH(X.SCHEDSTART) = 10 AND YEAR(X.SCHEDSTART) = YEAR(P.SCHEDSTART)) AS Oct,
(SELECT SUM(X.QTYCALC) FROM PRODTABLE X WHERE MONTH(X.SCHEDSTART) = 11 AND YEAR(X.SCHEDSTART) = YEAR(P.SCHEDSTART)) AS Nov,
(SELECT SUM(X.QTYCALC) FROM PRODTABLE X WHERE MONTH(X.SCHEDSTART) = 12 AND YEAR(X.SCHEDSTART) = YEAR(P.SCHEDSTART)) AS Dec
FROM       PRODTABLE P
GROUP BY YEAR(P.SCHEDSTART)

您应该检查(PIVOT和此)有关绩效/执行计划......