【每日一练:SQL】写一条SQL统计连续三个月金额大于0及每个月的金额

写一条SQL统计连续在三个月金额大于0及展现每个月的金额

需求:

下面是表FEE,字段是month(月份),service_id(电话号码),fee(出帐金额),请参看下面要求:
   Month      service_id       fee
   201801     13012345678     50
   201802     13012345678     60
   201803     13012345678     45
   201801     13012345677     70
   201802     13012345677     80
   201803     13012345676     60
   201801     13012345675     50
   201802     13012345675     40
   201803     13012345675     70
请写出连续在201801,201802,201803三个月出帐金额大于0的电话号码,及201801出帐金额,201802出帐金额,201803出帐金额。
(通过一个sql语句实现,可以通过case when 的复杂查询语句实现。)

解答:

数据库版本:oracle 11g

--创建表和插入数据

create table fee(month int,service_id bigint,fee int);
insert into fee values(201801,13012345678,50);
insert into fee values(201802,13012345678,60);
insert into fee values(201803,13012345678,45);
insert into fee values(201801,13012345677,70);
insert into fee values(201802,13012345677,80);
insert into fee values(201803,13012345676,60);
insert into fee values(201801,13012345675,50);
insert into fee values(201802,13012345675,40);
insert into fee values(201803,13012345675,70);
commit;

--SQL语句
 

select service_id, month
       , case when month = 201801 then sum(fee)
              when month = 201802 then sum(fee)
              when month = 201803 then sum(fee)
         end as fee
  from fee f
 where f.service_id in (--查询出三个月都出账的电话号码
                        select service_id
                          from fee
                         where month = 201801
                           and service_id in (select service_id from fee where month = 201802)
                           and service_id in (select service_id from fee where month = 201803)
                         )
 group by service_id, month
 order by 1;

SERVICE_ID	MONTH	FEE
13012345675	201801	50
13012345675	201802	40
13012345675	201803	70
13012345678	201801	50
13012345678	201802	60
13012345678	201803	45

注意:这里每个月有金额的话,默认是都大于0的,如果有0的话也简单,只需要再加一个大于0的条件;

 

你可能感兴趣的:(每日一练,蒙夛的每日一练(SQL,逻辑等))