【348天】我愛刷題系列107(2018.01.19)

叨叨兩句

  1. ~

SQL習題002

1

CREATE TABLE tb_amount1 (
  year varchar2(4) DEFAULT NULL,
  month number(2) DEFAULT NULL,
  amount number(3,2) DEFAULT NULL
); 

insert  into tb_amount1(year,month,amount) values ('2011',1,1.10);
insert  into tb_amount1(year,month,amount) values ('2011',2,1.20);
insert  into tb_amount1(year,month,amount) values ('2011',3,1.30);
insert  into tb_amount1(year,month,amount) values ('2011',4,1.40);
insert  into tb_amount(year,month,amount) values ('2012',1,2.10);
insert  into tb_amount(year,month,amount) values ('2012',2,2.20);
insert  into tb_amount(year,month,amount) values ('2012',3,2.30);
insert  into tb_amount(year,month,amount) values ('2012',4,2.40);
-- 1. 以 1 爲例, 將 1月份的數據豎起來
select year,case month when 1 then amount end m1 from tb_amount; 

-- 2. 將空行全都取掉
select year,sum(case month when 1 then amount end) m1 from tb_amount group by year; 

-- 3. 結果
select year,
       sum(case month when 1 then amount end) m1,
       sum(case month when 2 then amount end) m2,
       sum(case month when 3 then amount end) m3,
       sum(case month when 4 then amount end) m4 
from tb_amount group by year;
相關文章
相關標籤/搜索