2017-04-26 2 views
1

Ich suche einige Daten aus dieser AbfrageSQL Server Pivot-Code Hilfe benötigt

select 
    count(*) as total_customers, 
    sum(last_year) as customers_in_last_year 
    sum(two_years) as customers_in_last_2_years 
from 
    Customers 

, die dieses Ergebnis zurückgibt zu schwenken:

total_customers customers_in_last_year customers_in_last_2_years 
500     100       200 

Was ich tun möchte, dass auf die unten kippen , irgendeine Hilfe?

total_customers    500 
customers_in_last_year   100 
customers_in_last_2_years  200 

Dank

Antwort

0
CREATE TABLE #Table11 
    ([total_customers] int, [customers_in_last_year] int, [customers_in_last_2_years] int) 
; 

INSERT INTO #Table11 
    ([total_customers], [customers_in_last_year], [customers_in_last_2_years]) 
VALUES 
    (500, 100, 200) 


select [subject],total_customerss as total_customers 
from #Table11 s 
unpivot 
(
    total_customerss 
    for subject in ([total_customers], [customers_in_last_year], [customers_in_last_2_years]) 
) u; 

Ausgang

total_customers    500 
customers_in_last_year  100 
customers_in_last_2_years  200 

anhängen Ihre Abfrage wie dieses Gesetzt

SELECT [subject] 
    ,total_customerss AS total_customers 
FROM (
    SELECT count(*) AS total_customers 
     ,sum(last_year) AS customers_in_last_year, sum(two_years) AS customers_in_last_2_years 
    FROM Customers 
    ) s 
unpivot(total_customerss FOR subject IN (
      [total_customers] 
      ,[customers_in_last_year] 
      ,[customers_in_last_2_years] 
      )) u; 
0

dass Sie speichern Ihr Ergebnis in eine Tabelle namens YourResult (welche sein kann beim Tabelle emp, Variablentabelle), können Sie wie folgt vorgehen:

select 'total_customers' as col, total_customers as val from YourResult 
union all 
select 'customers_in_last_year' as col, customers_in_last_year as val from YourResult 
union all 
select 'customers_in_last_2_years' as col, customers_in_last_2_years as val from YourResult 

prüfen ein funktionierendes Beispiel here.