用一條sql語句實現下面結果:
怎麼把這樣一個表:
year month amount
1991 1 1.1
1991 2 1.2
1991 3 1.3
1991 4 1.4
1992 1 2.1
1992 2 2.2
1992 3 2.3
1992 4 2.4
查成這樣一個結果
year m1 m2 m3 m4
1991 1.1 1.2 1.3 1.4
1992 2.1 2.2 2.3 2.4
如下答案,可能表名不一樣。
****************
個人答案1:
SQL> select year,
max(decode(month,1,amount)) as m1,
max(decode(month,2,amount)) as m2,
max(decode(month,3,amount)) as m3,
max(decode(month,4,amount)) as m4
from mrtest
group by year;
*********** 個人答案2: SQL> select a.year year,a.amount m1,b.amount m2,c.amount m3,d.amount m4 from mrtest a,mrtest b,mrtest c,mrtest d where a.month=1 and b.month=2 and c.month=3 and d.month=4 and a.year=b.year and b.year=c.year and c.year=d.year; ***************** 其它答案3: select year, (select amount from aaa m where month=1 and m.year=aaa.year) as m1, (select amount from aaa m where month=2 and m.year=aaa.year) as m2, (select amount from aaa m where month=3 and m.year=aaa.year) as m3, (select amount from aaa m where month=4 and m.year=aaa.year) as m4 from aaa group by year ***************************** 答案5: select year, sum(case when month = '1' then amount else '0' end) as m1, sum(case when month = '2' then amount else '0' end) as m2, sum(case when month = '3' then amount else '0' end) as m3, sum(case when month = '4' then amount else '0' end) as m4 from table_name group by year