2017-04-26 1 views
1

Je cherche à faire pivoter des données de cette requêtecode pivot SQL Server avait besoin d'aide

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

qui retourne cet ensemble de résultats:

total_customers customers_in_last_year customers_in_last_2_years 
500     100       200 

Ce que je veux faire est flip au-dessous , de l'aide?

total_customers    500 
customers_in_last_year   100 
customers_in_last_2_years  200 

Merci

Répondre

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; 

sortie

total_customers    500 
customers_in_last_year  100 
customers_in_last_2_years  200 

append votre requête comme ceci

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

Supposant que vous stockez votre résultat dans une table appelée YourResult (qui peut être à table emp, table variable), vous pouvez effectuer les opérations suivantes:

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 

Vérifiez un exemple de travail here.