1

这是我的基表:

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 中的数据透视表,但不能写任何能给出接近我想要的结果的东西

4

2 回答 2

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

SQL小提琴

于 2012-10-03T05:37:02.297 回答
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
于 2012-10-03T08:22:10.717 回答