sql 表透视或转换
我有一个如下所示的数据表,
User Year Points Value
A 1997 1 10
A 1997 2 30
A 1997 3 40
A 1999 1 70
B 1993 1 7
B 1993 3 4
C 2001 1 10
.....
我希望该表被转换为这样:
User Year Points1 Points2 Points3 ....
A 1997 10 30 40
A 1999 70 null null
B 1993 7 null 4
C 2001 10 null null
......
点的范围在编译时是未知的,所以它不仅仅是从 1 到 3。 这几乎就像将点作为新表中的列标题一样。我认为 SQL PIVOT 是一个不错的选择,但我没有任何运气使用它。我正在使用 SQL 2008。
I have a table of data like the following
User Year Points Value
A 1997 1 10
A 1997 2 30
A 1997 3 40
A 1999 1 70
B 1993 1 7
B 1993 3 4
C 2001 1 10
.....
I want the table to be transformed as such:
User Year Points1 Points2 Points3 ....
A 1997 10 30 40
A 1999 70 null null
B 1993 7 null 4
C 2001 10 null null
......
The range of the Points is unknown at compile time, so it's not just from 1 to 3.
It almost like making the Points as the column header in the new table. I suppose SQL PIVOT is a good option, but I haven't got any luck playing with it. I'm using SQL 2008.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
既然您提到了
SQL PIVOT
,我猜您正在使用 SQL Server 2005 或更高版本或 Oracle 11gSQL 2005
请参阅此 data.se 查询
Oracle 11g
如果您使用的是 Oracle 11g,它会是这样的(不确定字段别名)
Since you mentioned
SQL PIVOT
I'm guessing you're using SQL Server 2005 or later or Oracle 11gSQL 2005
see working example at this data.se query
Oracle 11g
If you're using Oracle 11g it would be somthing like this (not sure about the field alias)
也许这会有所帮助:
首先创建一些测试数据:
连接列:
然后创建动态sql并执行它:
因为我不想要点表:
Maybe this will help:
First create some test data:
The concating the columns:
Then create the dynamic sql and executing it:
And the because I don't want the point table: