将4行(1列)转换为5列(1行)时的PIVOT问题

时间:2010-08-18 20:15:29

标签: sql-server-2005 tsql pivot

我有一个包含一些行但只有一行DATETIME类的表变量,如下所示:

[Day]
2010-08-03
2010-08-04
2010-08-10
2010-08-11

我需要在一些列上显示但只在一行中显示。 我的结果集将限制为5行,那么我也可以限制为5列。 我需要的例子:

[Day1]      [Day2]      [Day3]      [Day4]      [Day5]
2010-08-03  2010-08-04  2010-08-10  2010-08-11  NULL

我试图在SQL Server 2005中使用PIVOT。 但是所有的例子都使用了更多的列来聚合值,然后我就不理解了。

这是我正在尝试的查询:

SELECT r.* FROM (SELECT ROW_NUMBER() OVER (ORDER BY Day ASC) Line, Day FROM @MyDays) AS o
PIVOT (MIN(Line) FOR Day IN (Day1, Day2, Day3, Day4, Day5)) AS r

但结果全是NULL:

[Day1]  [Day2]  [Day3]  [Day4]  [Day5]
NULL    NULL    NULL    NULL    NULL

有人能告诉我我做错了吗?

2 个答案:

答案 0 :(得分:3)

Row_Number()只返回列表1-5中的数字,因此它不会匹配列表“Day1,Day2,Day3,Day4,Day5”中的任何内容。我已将“Day”添加到前面,所以它会。

另外你有MIN(Line) FOR Day IN,这需要另外。它是您想要显示的Day的值。

;with mydays as
(

SELECT '2010-08-03' AS [Day] UNION
SELECT '2010-08-04' AS [Day] UNION
SELECT '2010-08-10' AS [Day] UNION
SELECT '2010-08-11' AS [Day] 
)
SELECT r.* FROM (
   SELECT 
      'Day' + CAST( ROW_NUMBER() OVER (ORDER BY Day ASC)as varchar(10)) Line, 
       Day 
   FROM mydays) AS o
PIVOT (MIN([Day]) FOR Line IN (Day1, Day2, Day3, Day4, Day5)) AS r

答案 1 :(得分:1)

这是另一个不涉及Pivot声明的解决方案:

With RawData As
    (
    Select '2010-08-03' AS [Day]
    Union All Select '2010-08-04' 
    Union All Select '2010-08-10'
    Union All Select '2010-08-11'
    )
    , NumberedItems As
    (
    Select Day, Row_Number() Over( Order By Day ) As Line
    From RawData
    )
Select Min ( Case When Line = 1 Then [Day] End ) As Day1
    , Min ( Case When Line = 2 Then [Day] End ) As Day2
    , Min ( Case When Line = 3 Then [Day] End ) As Day3
    , Min ( Case When Line = 4 Then [Day] End ) As Day4
    , Min ( Case When Line = 5 Then [Day] End ) As Day5
From NumberedItems