我的MS SQL服务器中有以下表格:
User | Item | Date
1 | A | 2015-03-01
1 | B | 2015-03-03
1 | C | 2015-03-02
1 | A | 2015-03-05
2 | C | 2015-03-01
2 | C | 2015-03-03
2 | B | 2015-03-02
此表格应汇总/转动/转置为:
User | 1st_item | 2nd_item | 3rd_item | 4th_item
1 | A | C | B | A
2 | C | B | C | NULL
(项目的顺序由原始数据中的日期定义。) 不幸的是,我不知道如何到达那里...... 理想情况下,该解决方案也适用于灵活数量的项目(未固定为4,如示例所示)。
到目前为止我尝试了什么:
提前感谢您的帮助和/或提示!
答案 0 :(得分:0)
透视示例
SELECT [User],
[1] AS [1st_item],
[2] AS [2nd_item],
[3] AS [3rd_item],
[4] AS [4th_item]
FROM (SELECT [User],
[Item],
ROW_NUMBER() OVER (PARTITION BY [User] ORDER BY [Date]) Rn
FROM myTable) mt
PIVOT (
MAX([Item])
FOR Rn IN ([1],[2],[3],[4])
) p