PIVOT语句的解决方法

时间:2017-04-04 18:43:43

标签: sql sql-server tsql

我有这个查询,花了2分钟来解决,我需要找到一个解决方法,我知道UNPIVOT有一个更好的解决方案使用CROSS APPLY,PIVOT有什么类似的吗?

SELECT [RowId],  [invoice date], [GL], [Entité], [001], [Loc], [Centre Cout], [Compte_1], [Interco_1], [Futur_1], [Department], [Division], [Compagnie], [Localisation], [Centre/Cout], [Compte], [Interco], [Futur], [Account], [Mobile], [Last Name], [First Name], [license fee], [GST], [HST], [PST], [Foreign Tax], [Sales Tax License], [Net Total], [Total], [ServiceType], [Oracle Cost Center], [CTRL], [EXPENSE], [Province]
        FROM 
                (SELECT fd.[RowId], fc.[ColumnName], fd.[Value]
                    FROM dbo.FileData fd
                INNER JOIN dbo.[FileColumn] fc  
                    ON fc.[FileColumnId] = fd.[FileColumnId]               
                WHERE FileId = 1
                    AND TenantId = 1) x
        PIVOT
        (
        MAX(Value)
        FOR [ColumnName] IN ( [invoice date], [GL], [Entité], [001], [Loc], [Centre Cout], [Compte_1], [Interco_1], [Futur_1], [Department], [Division], [Compagnie], [Localisation], [Centre/Cout], [Compte], [Interco], [Futur], [Account], [Mobile], [Last Name], [First Name], [license fee], [GST], [HST], [PST], [Foreign Tax], [Sales Tax License], [Net Total], [Total], [ServiceType], [Oracle Cost Center], [CTRL], [EXPENSE], [Province])
        ) AS p

1 个答案:

答案 0 :(得分:1)

Pivots很棒,但条件聚合也是如此。此外,没有必要的数据类型或转换

SELECT [RowId]
      ,[invoice date] = max(case when [FileColumnId] = ??? then Value end)
      ,[GL]           = max(case when [FileColumnId] = ??? then Value end)
      ,... more fields
 FROM  dbo.FileData fd
 WHERE FileId = 1
  AND TenantId = 1
 Group By [RowId]
  

修改

您可以添加联接以使其更具可读性。