编写查询以从给定表中获取所需的转换输出

时间:2018-08-18 06:53:10

标签: sql sql-server database data-analysis

the First table is given dbo.sales table

the desired output

我希望查询的结果可以如第二张照片所示,因为数据在第一张表(照片)中给出

3 个答案:

答案 0 :(得分:0)

这种将列转换为行的转换在SQL中称为Pivot。

    SELECT Region,[2010],[2011],[2012],[2013],[2015]
    FROM 
        (SELECT *
        FROM SalesTable) AS SourceTable
    PIVOT
    (
       Avg(Sales)
       FOR Year in 
      ([2010],[2011],[2012],[2013],[2015])
    ) as pvt;

答案 1 :(得分:0)

尝试一下:

with tmp as (
select f1.region, f1.Year, sum(f1.Sales) Sales 
from dbo.sales f1
group by f1.region, f1.Year
)
select distinct f1.Region, 
f2.Sales as [2010], f3.Sales as [2011], f4.Sales as [2012], f5.Sales as [2013], f6.Sales as [2014], f7.Sales as [2015] 
from tmp f1
left outer join tmp f2 on f1.Region=f2.Region and f2.year=2010
left outer join tmp f3 on f1.Region=f3.Region and f3.year=2011
left outer join tmp f4 on f1.Region=f4.Region and f4.year=2012
left outer join tmp f5 on f1.Region=f5.Region and f5.year=2013
left outer join tmp f6 on f1.Region=f6.Region and f6.year=2014
left outer join tmp f7 on f1.Region=f7.Region and f7.year=2015

答案 2 :(得分:0)

我更喜欢条件聚合来进行透视:

select id,
       max(case when year = 2010 then sales end) as sales_2010,
       max(case when year = 2011 then sales end) as sales_2011,
       max(case when year = 2012 then sales end) as sales_2012,
       max(case when year = 2013 then sales end) as sales_2013,
       max(case when year = 2014 then sales end) as sales_2014,
       max(case when year = 2015 then sales end) as sales_2015
from t
group by id
order by id;