自动扩展SQL数据透视表中的列数

时间:2017-05-05 05:20:52

标签: sql sql-server pivot

我需要帮助才能将SQL中的列转换为行(使用SQL Server 2016)。

目前我有:

SELECT Customer
    , ItemName
FROM dbSales

给出:

Customer | ItemName
-------------------
Person1  | Product1
Person1  | Product2
...      | ...
Person1  | ProductN
Person2  | Product5
Person2  | ProductX
...      | ...
PersonN  | ProductN

我想制作:

Customer | Item1    | Item2    | ... | ItemN
-----------------------------------------------
Person1  | Product1 | Product2 | ... | ProductN
Person2  | Product5 | ProductX | ... | NULL
...      | ...      | ...      | ... | ...
PersonN  | ProductN | NULL     | ... | NULL

经过一些搜索和阅读后,我找到https://community.spiceworks.com/topic/973727-sql-how-to-convert-multiple-rows-into-single-rows-with-more-columns并将接受的解决方案改编为:

WITH groupitems
AS (SELECT ROW_NUMBER() OVER (PARTITION BY Customer ORDER BY Customer) AS RowID
        , *
    FROM dbSales
    )
SELECT Customer AS [CustomerName],
    MIN(Item1) AS Item1
    MIN(Item2) AS Item2
    MIN(Item3) AS Item3
FROM (SELECT ROW_NUMBER() OVER (PARTITION BY Customer ORDER BY Customer) AS RowID
    , Customer
    , 'Item' + CAST(RowID AS VARCHAR) AS ItemNum
    , Item
    FROM groupitems) AS pvt
PIVOT (MIN(Item)
    FOR ItemNum in ([Item1], [Item2], [Item3])) AS PVT
GROUP BY Customer;

这将产生:

Customer | Item1    | Item2    | Item3
-----------------------------------------
Person1  | Product1 | Product2 | Product3
Person2  | ProductX | NULL     | NULL
...      | ...      | ...      | ...
PersonN  | ProductY | ProductZ | NULL

作为SQL的新手,我如何调整它以自动扩展表中的列数,这样我就不需要硬编码Item列的数量了?

0 个答案:

没有答案
相关问题