将 4 行(1 列)转换为 5 列(1 行)时的 PIVOT 问题
我有一个表 var,其中包含一些行,但只有一列 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
有人可以告诉我我做错了什么吗?
I have a table var with some rows but only one column of type DATETIME, like this:
[Day]
2010-08-03
2010-08-04
2010-08-10
2010-08-11
I need to show on some columns but in only one row.
My result set will be limited to 5 rows, then I can limit to 5 columns too.
Example of what I need:
[Day1] [Day2] [Day3] [Day4] [Day5]
2010-08-03 2010-08-04 2010-08-10 2010-08-11 NULL
I was trying to do it using PIVOT in SQL Server 2005.
But all examples uses more columns to agregate values, then I'm not understanding.
This is the query I was trying:
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
But the result is all NULL:
[Day1] [Day2] [Day3] [Day4] [Day5]
NULL NULL NULL NULL NULL
Could someone show me what I'm doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Row_Number()
仅返回列表 1-5 中的一个数字,因此它不会与列表“Day1、Day2、Day3、Day4、Day5”中的任何内容匹配。我已经在前面附加了“日”,这样就可以了。另外,您还有
MIN(Line) FOR Day IN
,这需要反过来。这是您要显示的Day
的值。Row_Number()
just returns a number in the list 1-5 so it isn't going to match anything in your list "Day1, Day2, Day3, Day4, Day5". I have appended "Day" onto the front so it will.Additionally you have
MIN(Line) FOR Day IN
, This needs to be the otherway around. It is the value ofDay
that you are wanting to display.这是另一个不涉及 Pivot 语句的解决方案:
Here's another solution which does not involve the Pivot statement: