多行记录到一行

时间:2015-03-18 06:47:24

标签: sql sql-server sql-server-2014

我需要转换这个给定的表:

ArticleId  | SymbolId
-----------+----------
1          | 1
1          | 2
1          | 3
2          | 6
2          | 7
2          | 3
2          | 4
2          | 5

进入另一个这样的表:

ArticleId  |  Symbol1  | Symbol2  | Symbol3  | Symbol4  | Symbol5
-----------+-----------+----------+----------+----------+---------
1          |  1        | 2        | 3        | NULL     | NULL
2          |  6        | 7        | 3        | 4        | 5

有一种简单的方法吗?每ArticleId总共最多有5条记录。无需特殊订单。

1 个答案:

答案 0 :(得分:2)

您可以使用MAX(CASE WHEN END)

;WITH YourTable(ArticleId, SymbolId) AS(
    SELECT 1, 1 UNION ALL
    SELECT 1, 2 UNION ALL
    SELECT 1, 3 UNION ALL
    SELECT 2, 6 UNION ALL
    SELECT 2, 7 UNION ALL
    SELECT 2, 3 UNION ALL
    SELECT 2, 4 UNION ALL
    SELECT 2, 5 
)
SELECT
    ArticleId,
    Symbol1 = MAX(CASE WHEN RN = 1 THEN SymbolId END),
    Symbol2 = MAX(CASE WHEN RN = 2 THEN SymbolId END),
    Symbol3 = MAX(CASE WHEN RN = 3 THEN SymbolId END),
    Symbol4 = MAX(CASE WHEN RN = 4 THEN SymbolId END),
    Symbol5 = MAX(CASE WHEN RN = 5 THEN SymbolId END)
FROM(
    SELECT *,
        RN = ROW_NUMBER() OVER(PARTITION BY ArticleId ORDER BY (SELECT NULL))
    FROM YourTable
)t
GROUP BY ArticleId

使用PIVOT

;WITH YourTable(ArticleId, SymbolId) AS(
    SELECT 1, 1 UNION ALL
    SELECT 1, 2 UNION ALL
    SELECT 1, 3 UNION ALL
    SELECT 2, 6 UNION ALL
    SELECT 2, 7 UNION ALL
    SELECT 2, 3 UNION ALL
    SELECT 2, 4 UNION ALL
    SELECT 2, 5 
)
SELECT
    ArticleId,
    Symbol1 = [1], 
    Symbol2 = [2], 
    Symbol3 = [3], 
    Symbol4 = [4], 
    Symbol5 = [5]
FROM (
    SELECT *,
        RN = ROW_NUMBER() OVER(PARTITION BY ArticleId ORDER BY (SELECT NULL))
    FROM YourTable
)t
PIVOT (
    MAX(t.SymbolId)
    FOR RN IN ([1], [2], [3], [4], [5])
)p