2017-04-04 44 views
1

我有這個查詢,需要2分鐘解決,我需要找到一個解決方法,我知道UNPIVOT有一個更好的解決方案使用CROSS APPLY,有什麼類似的PIVOT?解決方案爲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

這是一個很好的開始。 http://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/ –

回答

1

樞軸是偉大的,但也有條件聚合。此外,就沒有數據類型conficts或轉換必要

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] 

編輯

你可以加回加盟,使其更具可讀性。