year month, amount
1991 1 1.1
1991 2 1.2
1991 3 1.3
1991 4 1.4
1992 1 2.1
1992 1 2.1
1992 2 2.2
1992 3 2.3
1992 4 2.4
一个表里面的数据如上。年月和营业金额。
现在写一个sql将这个表转成横表如下:
year m1 m2 m3 m4
1991 1.1 1.2 1.3 1.4
1992 4.2 2.2 2.3 2.4
请问该怎么写这条SQL语句? 分年月算出总的营业额。
1991 1 1.1
1991 2 1.2
1991 3 1.3
1991 4 1.4
1992 1 2.1
1992 1 2.1
1992 2 2.2
1992 3 2.3
1992 4 2.4
一个表里面的数据如上。年月和营业金额。
现在写一个sql将这个表转成横表如下:
year m1 m2 m3 m4
1991 1.1 1.2 1.3 1.4
1992 4.2 2.2 2.3 2.4
请问该怎么写这条SQL语句? 分年月算出总的营业额。
sum(decode(month,1,amount,0)) m1,
sum(decode(month,2,amount,0)) m2,
sum(decode(month,3,amount,0)) m3,
sum(decode(month,4,amount,0)) m4
from 表
group by year
sum(case month when 1 then amount else 0 end) m1,
sum(case month when 2 then amount else 0 end) m2,
sum(case month when 3 then amount else 0 end) m3,
sum(case month when 4 then amount else 0 end) m4
from tb
group by year