这是我的基础表:
Region year carsSold bicyclesSold
RegX 1999 50 100
RegX 2000 150 30
RegY 1998 60 40
我希望得到的结果是:
Region Year 1998 1999 2000
RegX carsSold 0 50 150
bicyclesSold 0 100 30
RegY carsSold 60 0 0
bicyclesSold 40 0 0
有没有办法在sql server中执行此操作?有没有办法在Excel中执行此操作?这种数据表示的最佳解决方案是什么。你能建议任何适合的软件吗?
我知道在sql server中透视表,但是不能写任何能让结果接近我想要的东西
答案 0 :(得分:3)
select P.Region,
P.Item,
isnull(P.[1998], 0) as [1998],
isnull(P.[1999], 0) as [1999],
isnull(P.[2000], 0) as [2000]
from YourTable
unpivot (ItemsSold for Item in (carsSold, bicyclesSold)) as U
pivot (sum(ItemsSold) for year in ([1998], [1999], [2000])) as P
order by P.Region, P.Item
答案 1 :(得分:1)
作为替代方案,仅限ANSI-92兼容代码。哎呀,你甚至可以在SQLite中运行它,除了关于对列名称进行方括号的部分。
当你说exactly what I want
select
case when veh.iscar=1 then t.region else '' end Region,
veh.type [Year],
max(case when t.year = 1998
then carsSold*iscar + bicyclesSold*(1-iscar) else 0 end) [1998],
max(case when t.year = 1999
then carsSold*iscar + bicyclesSold*(1-iscar) else 0 end) [1999],
max(case when t.year = 2000
then carsSold*iscar + bicyclesSold*(1-iscar) else 0 end) [2000]
from YourTable t
cross join (
select 'carsSold',1 union all
select 'bicyclesSold',0) veh(type,iscar)
group by t.region, veh.type, veh.iscar
order by t.region, type desc;
>>
Region Year 1998 1999 2000
RegX carsSold 0 50 150
bicyclesSold 0 100 30
RegY carsSold 60 0 0
bicyclesSold 40 0 0