SQL Server 2008展平行

时间:2015-05-21 20:28:01

标签: sql-server grouping

我需要将最初每个用户有4行的记录集展平为1行。我开始使用PIVOT功能,但有2个字段需要展平(并且枢轴没有按预期工作)。

当前的数据结构:

  ContactEmail      Scenario    TRE      Updated_On
  -------------------------------------------------------------
  email@email.com   WTD         0.9785  2015-05-12 22:35:14.993
  email@email.com   MTD         0.9817  2015-05-12 22:35:57.780
  email@email.com   QTD         0.9542  2015-05-12 23:16:35.227
  email@email.com   YTD         0.9522  2015-05-12 23:39:56.533

结果应为:

  ContactEmail     WTD_TRE WTD_TRE_Updated   MTD_TRE MTD_TRE_Updated  QTD_TRE QTD_TRE_Updated  YTD_TRE YTD_TRE_Updated 
  --------------------------------------------------------------------------------------------------------------------
  email@email.com   0.9785  2015-05-12       0.9817  2015-05-12       0.9542  2015-05-12      0.9522  2015-05-12

如果您对我尝试过的PIVOT感到好奇,这里就是(TRE_ *都为空)

  SELECT *
  FROM (SELECT ContactEmail, Round((ISNULL(TRE, 0) * 100), 1) AS "TRE", Scenario, Updated_On
        FROM [server].[db].[schema].[table]) AS TREData
  PIVOT
  (
    SUM(TRE)
    FOR Scenario 
    IN ([TRE_WTD],[TRE_MTD],[TRE_QTD],[TRE_YTD])    
  ) AS PivotTable;

1 个答案:

答案 0 :(得分:1)

创建两个透视查询并加入它们......

WITH CurrentDataStructure as (
    SELECT 'email@email.com' ContactEmail, 
           'WTD' Scenario, 
           0.9785 TRE, 
           '2015-05-12 22:35:14.993' Updated_On
    UNION SELECT 'email@email.com', 'MTD', 0.9817, '2015-05-12 22:35:57.780'
    UNION SELECT 'email@email.com', 'QTD', 0.9542, '2015-05-12 23:16:35.227'
    UNION SELECT 'email@email.com', 'YTD', 0.9522, '2015-05-12 23:39:56.533'
), TREData as (
    SELECT ContactEmail, Round((ISNULL(TRE, 0) * 100), 1) TRE, Scenario, Updated_On 
    FROM CurrentDataStructure
), TREs AS (
    SELECT *
        FROM (SELECT ContactEmail, Scenario, TRE FROM TREData) TREData
    PIVOT
    (
        SUM(TRE)
        FOR Scenario 
        IN ([WTD],[MTD],[QTD],[YTD])    
    ) PivotTable
), TREsUpdated AS (
    SELECT *
        FROM (SELECT ContactEmail, Scenario, Updated_On FROM TREData) TREData
    PIVOT
    (
        MAX(Updated_On)
        FOR Scenario 
        IN ([WTD],[MTD],[QTD],[YTD])    
    ) PivotTable
)

SELECT t.ContactEmail, 
    t.WTD WTD_TRE, u.WTD WTD_TRE_Updated, 
    t.MTD MTD_TRE, u.MTD MTD_TRE_Updated, 
    t.QTD QTD_TRE, u.QTD QTD_TRE_Updated,
    t.YTD YTD_TRE, u.YTD YTD_TRE_Updated
FROM TREs as t
    INNER JOIN
TREsUpdated as u
    ON t.ContactEmail = u.ContactEmail

这是经过测试的,应该像它一样运行。