选择转换为表格

时间:2017-02-27 13:24:42

标签: sql sql-server

我有来自select查询的数据,看起来是这样的:

         Id                               EventName  Quantity
A930FF06-B9F2-4D06-A28E-00037E82DDB1    DiscountClick   40
A930FF06-B9F2-4D06-A28E-00037E82DDB1    DiscountLike    1
A930FF06-B9F2-4D06-A28E-00037E82DDB1    DiscountSave    11
A930FF06-B9F2-4D06-A28E-00037E82DDB1    DiscountView    2579
28D64EEB-97FB-45A9-AA4C-00359FF6FF42    DiscountClick   22
28D64EEB-97FB-45A9-AA4C-00359FF6FF42    DiscountSave    1
28D64EEB-97FB-45A9-AA4C-00359FF6FF42    DiscountView    971

我想将它转换为看起来像这样的表:

 Id                                     DiscountView   Discount...
A930FF06-B9F2-4D06-A28E-00037E82DDB1    2579
28D64EEB-97FB-45A9-AA4C-00359FF6FF42    971

我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

这是针对您的问题的动态数据透视查询。

  DECLARE @DynamicPivotQuery AS NVARCHAR(MAX),
        @PivotColumnNames AS NVARCHAR(MAX),
        @PivotSelectColumnNames AS NVARCHAR(MAX)

--Get distinct values of the PIVOT Column
SELECT @PivotColumnNames= ISNULL(@PivotColumnNames + ',','')
+ QUOTENAME(EventName)
FROM (SELECT DISTINCT EventName FROM test_table) AS Courses

--Get distinct values of the PIVOT Column with isnull
SELECT @PivotSelectColumnNames 
    = ISNULL(@PivotSelectColumnNames + ',','')
    + 'ISNULL(' + QUOTENAME(EventName) + ', 0) AS '
    + QUOTENAME(EventName)
FROM (SELECT DISTINCT EventName FROM test_table) AS Courses

--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
  N'SELECT Id, ' + @PivotSelectColumnNames + '
    FROM test_table
    pivot(sum(quantity) for EventName in (' + @PivotColumnNames + ')) as pvt';

--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery

enter image description here

答案 1 :(得分:0)

这是pivot()的传统交叉表/条件聚合版本:

select
    Id
  , DiscountView = sum(case when EventName = 'DiscountView' then Quantity end)
  , DiscountSave = sum(case when EventName = 'DiscountSave' then Quantity end)
  , DiscountLike = sum(case when EventName = 'DiscountLike' then Quantity end)
from t
group by Id

pivot()版本:

select
    Id
  , DiscountView
  , DiscountSave
  , DiscountLike
from t
pivot (sum(Quantity) for EventName in (DiscountView, DiscountSave, DiscountLike)) pvt