表1
年 月 型号 类别 总价
2012 8 001 A 10
2012 8 001 B 11
2012 8 001 C 12
2012 8 002 A 13
2012 8 002 B 14
2012 8 002 C 15
2012 9 001 A 16
2012 9 001 B 17
2012 9 001 C 18
表2
年 月 型号 A总价 B总价 C总价
2012 8 001 10 11 12
2012 8 002 13 14 15
2012 9 001 16 17 18
问:怎样用sql语句将表1中相同年、月、型号,按照类别分类总价,即弄成表2的样式?
年 月 型号 类别 总价
2012 8 001 A 10
2012 8 001 B 11
2012 8 001 C 12
2012 8 002 A 13
2012 8 002 B 14
2012 8 002 C 15
2012 9 001 A 16
2012 9 001 B 17
2012 9 001 C 18
表2
年 月 型号 A总价 B总价 C总价
2012 8 001 10 11 12
2012 8 002 13 14 15
2012 9 001 16 17 18
问:怎样用sql语句将表1中相同年、月、型号,按照类别分类总价,即弄成表2的样式?
--如果类别太多,用动态语句,baidu下行列转换
with t(year,month,pro,type,amount) as(
select 2012,8,'001','A',10 from dual
union all select 2012,8,'001','B',11 from dual
union all select 2012,8,'001','C',12 from dual
union all select 2012,8,'002','A',13 from dual
union all select 2012,8,'002','B',14 from dual
union all select 2012,8,'002','C',15 from dual
union all select 2012,9,'001','A',16 from dual
union all select 2012,9,'001','B',17 from dual
union all select 2012,9,'001','C',18 from dual
)
select year 年,month 月,pro 型号,
max(decode(type,'A',amount,0)) A总价,
max(decode(type,'B',amount,0)) B总价,
max(decode(type,'C',amount,0)) C总价
from t
group by year,month,pro
order by year,month,pro;
sum(decode(类别, 'A', 总价)) A总价,
sum(decode(类别, 'B', 总价)) B总价,
sum(decode(类别, 'C', 总价)) C总价
from t group by 年, 月, 型号;
(select 年, 月, 型号, 类别, 总价 from t)
pivot (
sum(总价) for 类别 in (
'A' as A总价,
'B' as B总价,
'C' as C总价
)
)
select 年, 月, 型号,
sum(decode(类别, 'A', 总价)) A总价,
sum(decode(类别, 'B', 总价)) B总价,
sum(decode(类别, 'C', 总价)) C总价
from t group by 年, 月, 型号;
上面的语句得不到你要的结果吗?