地点 品名 销量
-------------------
甲 A 100
甲 B 200
甲 C 130
乙 B 50
乙 D 80
丙 A 200
丙 B 400
形成一个如下的报表:
品名
地点 | A B C D
------------------------------------——
甲 | 100 200 300
乙 | 50 80
丙 | 200 400
用什么办法做最简单?
应怎样做才最省事?
...全文
4714打赏收藏
表的转换问题
要将如下的表 地点 品名 销量 ------------------- 甲 A 100 甲 B 200 甲 C 130 乙 B 50 乙 D 80 丙 A 200 丙 B 400 形成一个如下的报表: 品名 地点 | A B C D ------------------------------------—— 甲 | 100 200 300 乙 | 50 80 丙 | 200 400 用什么办法做最简单? 应怎样做才最省事?
select 地点,
sum(case when 品名='A' then 销量 else 0 end) as A,
sum(case when 品名='B' then 销量 else 0 end) as B,
sum(case when 品名='C' then 销量 else 0 end) as C,
sum(case when 品名='D' then 销量 else 0 end) as D
from tablename
grou by 地点
不过结果有点不一样:
品名
地点 | A B C D
------------------------------------——
甲 | 100 200 300 0
乙 | 0 50 0 80
丙 | 200 400 0 0
select distinct 地点,
(select sum(销量) from tablename where 品名='A') as A,
(select sum(销量) from tablename where 品名='B') as B,
(select sum(销量) from tablename where 品名='C') as C,
(select sum(销量) from tablename where 品名='D') as D
from tablename
sql server :
如果品名有限可知:
select 地点,
Nullif(sum(case when 品名='A' then 销量 else 0 end),0) as A,
Nullif(sum(case when 品名='B' then 销量 else 0 end),0) as B,
Nullif(sum(case when 品名='C' then 销量 else 0 end),0) as C,
Nullif(sum(case when 品名='D' then 销量 else 0 end),0) as D
from tablename
grou by 地点