在SQL中整合和透视数据

时间:2016-08-16 20:41:12

标签: sql sql-server

我有一个描述销售交易的数据源,格式如下:

    Transaction |    Date   | Location |    UPC    | LineNumber
----------------+-----------+----------+-----------+------------
         123    | 7/2/2016  | Store A  | 123456789 |      1
         123    | 7/2/2016  | Store A  | 123965478 |      2
         124    | 7/2/2016  | Store A  | 123456789 |      1
         124    | 7/2/2016  | Store A  | 123459879 |      2
         124    | 7/2/2016  | Store A  | 123456789 |      3
         123    | 7/3/2016  | Store B  | 123456789 |      1
         123    | 7/3/2016  | Store B  | 958685458 |      2

为了在我们的报告工具中使用这些数据,我需要使用Transaction-Location as Unique和UPC作为基于行号的列进行格式化:

Transaction |    Date   |  UPC 1    |   UPC 2   |  UPC 3
------------+-----------+-----------+----------
123-Store A | 7/2/2016  | 123456789 | 123965478 |   NULL
124-Store A | 7/2/2016  | 123456789 | 123459879 | 123456789
123-Store B | 7/3/2016  | 123456789 | 958685458 |   NULL

感谢任何想法

1 个答案:

答案 0 :(得分:1)

标准PIVOT会做到这一点。您只需在调用PIVOT之前在CTE或嵌套Select中定义连接的Transaction列。

DECLARE @Table AS TABLE ([Transaction] INT, Date DATE, Location VARCHAR(15), UPC INT, LineNumber INT)
INSERT INTO @Table ([Transaction], Date, Location, UPC, LineNumber)
VALUES
(123,'7/2/2016','Store A',123456789,1)
,(123,'7/2/2016','Store A',123965478,2)
,(124,'7/2/2016','Store A',123456789,1)
,(124,'7/2/2016','Store A',123459879,2)
,(124,'7/2/2016','Store A',123456789,3)
,(123,'7/3/2016','Store B',123456789,1)
,(123,'7/3/2016','Store B',958685458,2)

;WITH cteCombineTransLocation AS (
    SELECT
       CAST([Transaction] AS VARCHAR(50)) + '-' + Location as [Transaction]
       ,Date
       ,UPC
       ,LineNumber
    FROM
       @Table
)

SELECT
    [Transaction]
    ,[Date]
    ,[1] as UPC1
    ,[2] as UPC2
    ,[3] as UPC3
FROM
    cteCombineTransLocation
    PIVOT (
       MAX(UPC)
       FOR LineNumber IN ([1],[2],[3])
    ) p

如果你想要更多的UPC列或者这个数字是动态的,那么当评论者指出你可以使用动态sql时,你仍然需要先准备你的连接字段。