转置T-SQL查询

时间:2014-02-25 10:34:41

标签: sql-server tsql transpose

我有这样的查询:

SELECT 

SUM(
     CASE 
   WHEN 
START_DATE <= '2014-01-01' AND 
(END_DATE > '2014-01-01' OR END_DATE IS NULL)THEN 1 ELSE 0 END ) AS '201401',

SUM(
     CASE 
   WHEN 
START_DATE <= '2014-02-01' AND 
(END_DATE > '2014-02-01' OR END_DATE IS NULL)THEN 1 ELSE 0 END ) AS '201402')

    (etc)

FROM table

给我这个输出:

201401  201402   (etc)
485     498

我需要将其转换为例如给我这个输出:

201401  485
201402  498
(etc)

我发现的例子都是对数据进行分组;我只需要交换行和列。

3 个答案:

答案 0 :(得分:1)

您可以使用PIVOT执行此操作,但您的列号必须是有限的,并且给出如下内容:

PIVOT
    (
        SUM (Indicator) FOR Day IN (  [1],[2],[3],[4],[5],[6],[7],[8],[9],[10],
                    [11],[12],[13],[14],[15],[16],[17],[18],[19],[20],
                    [21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
    ) AS pvt

答案 1 :(得分:1)

你可以使用union转换:

SELECT 
'201401',
SUM(
     CASE 
   WHEN 
START_DATE <= '2014-01-01' AND 
(END_DATE > '2014-01-01' OR END_DATE IS NULL)THEN 1 ELSE 0 END )
FROM table

UNION ALL

SELECT 
'201402',
SUM(
     CASE 
   WHEN 
START_DATE <= '2014-02-01' AND 
(END_DATE > '2014-02-01' OR END_DATE IS NULL)THEN 1 ELSE 0 END )
FROM table

UNION ALL

SELECT 
    (etc)
FROM table

答案 2 :(得分:0)

你最好在客户端这样做。不在Db。

SELECT fields, x FROM (
    -- {{ your query here
    select 485 as [201401], 498 as [201402]
    -- }} your query here
) AS t
UNPIVOT (
    x FOR fields in ([201401], [201402])
) AS unpvt