需要SQL Server透视代码帮助

时间:2017-04-26 08:52:23

标签: sql-server pivot unpivot

我希望从此查询中转移一些数据

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

返回此结果集:

total_customers    customers_in_last_year    customers_in_last_2_years
500                  100                         200

我想要做的是将其翻到下面,任何帮助?

total_customers                500
customers_in_last_year         100
customers_in_last_2_years      200

由于

2 个答案:

答案 0 :(得分: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;

像这样追加您的查询

total_customers               500
customers_in_last_year        100
customers_in_last_2_years     200

答案 1 :(得分:0)

假设您将结果存储到名为YourResult的表(可以是临时表,变量表)中,您可以执行以下操作:

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

检查一个有效的例子here