分类统计
不知道哪里看到的问题,觉得思路还不错,记录下来,应该有更好的方法吧编号地区类型数量
0002中国b 250
0006中国c 130
0001中国a 100
0008中国b 30
0009中国c 80
0007美国c 190
0005美国a 210
0003美国a 50
0004美国b 180
地区类型a的总量 类型b的总量 类型c的总量
中国 100 280 210
美国 260 180 190
--create database test
create table tab1(
编号 varchar(20),
地区 varchar(20),
类型 varchar(20),
数量 int
)
insert into tab1 values('0002','中国','b',250)
insert into tab1 values('0006','中国','c',130)
insert into tab1 values('0001','中国','a','100')
insert into tab1 values('0008','中国','b','30')
insert into tab1 values('0009','中国','c','80')
insert into tab1 values('0007','美国','c','190')
insert into tab1 values('0005','美国','a','210')
insert into tab1 values('0003','美国','a','50')
insert into tab1 values('0004','美国','b','180')
select * from tab1
--select sum(数量) as 数量,地区,类型 as 类型 from tab1 group by 类型,地区
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的总量 from tab1 group by地区
页:
[1]