2017-02-11 4 views
1

Ich habe diese AbfrageWie verwenden Sie mehrere Spalten in Pivot?

SELECT [b].[BillID], 
     [b].[BillingCode], 
     [bc].[CurrentUsage], 
     [bc].[Rate], 
     [bc].[CurrentCost], 
     [c].[Title] 
INTO #Temp 
FROM [dbo].[Bills] AS [b] 
INNER JOIN [dbo].[BillCosts] AS [bc] ON [bc].[BillIDRef] = [b].[BillID] 
INNER JOIN [Base].[Costs] AS [c] ON [c].[CostID] = [bc].[CostIDRef] 

dieses Ergebnis

BillID  BillingCode   CurrentUsage Rate  CurrentCost Title 
----------- -------------------- ------------ ----------- ----------- ------ 
5   44545455    10   20   30   AvgTimes 
5   44545455    40   50   60   MaxTimes 

ich dieses Ergebnis benötigen:

BillID  BillingCode   AvgTimes Cost MaxTimes Cost AvgTimes Rate MaxTimes Rate AvgTimes Usage MaxTimes Usage 
----------- -------------------- -------------- -------------- -------------- ------------- -------------- --------------- 
5   44545455    30    60    20    50   10    40 

Ist es möglich, auf mehrere Spalten mit Dreh CurrentUsage,Cost,Rate? Wenn nicht möglich ist mit Pivot verwenden, Wie schreibe Abfrage?

Antwort

3

können Sie verwenden bedingte Aggregation:

SELECT [b].[BillID], 
     [b].[BillingCode], 
     MAX(CASE WHEN [c].[Title] = 'AvgTimes' THEN [bc].[CurrentUsage] END) AS [AvgTimes Usage], 
     MAX(CASE WHEN [c].[Title] = 'MaxTimes' THEN [bc].[CurrentUsage] END) AS [MaxTimes Rate], 
     MAX(CASE WHEN [bc].[Title] = 'AvgTimes' THEN [bc].[Rate] END) AS [AvgTimes Rate], 
     MAX(CASE WHEN [bc].[Title] = 'MaxTimes' THEN [bc].[Rate] END) AS [MaxTimes Usage], 
     MAX(CASE WHEN [bc].[Title] = 'AvgTimes' THEN [bc].[CurrentCost] END) AS [AvgTimes CurrentCost], 
     MAX(CASE WHEN [bc].[Title] = 'MaxTimes' THEN [bc].[CurrentCost] END) AS [MaxTimes CurrentCost] 
INTO #Temp 
FROM [dbo].[Bills] AS [b] 
INNER JOIN [dbo].[BillCosts] AS [bc] ON [bc].[BillIDRef] = [b].[BillID] 
INNER JOIN [Base].[Costs] AS [c] ON [c].[CostID] = [bc].[CostIDRef] 
GROUP BY [b].[BillID], [b].[BillingCode]