SQL面试题(十二)

问题:

表如下: 销售表:

   NO ,  NO2,  数量   日期

  1234 567890  33.5  2004-12-21

  1234 598701  44.8  2004-11-21

  1234 598701  45.2  2004-10-01

  1234 567890  66.5  2004-9-21

  3456 789065  22.5   2004-10-01

  3456 789065  77.5   2004-10-27

  3456 678901  48.5   2004-12-21

 

按月统计销售表中货物的销售量数

查询结果如下:

  No No2    九月,  十月,十一月,十二月

1234567890 66.5 ,  0  0    33.5

1234598701  0   , 45.2, 44.8, 0

3456789065, 0  ,  100  0  ,  0

3456678901, 0 ,    0    0    48.5

建表:

create table table_a (No int, No2 int,num double,itime date);
insert into table_a values 
(1234,567890,33.5,'2004-12-21'),
(1234,598701,44.8,'2004-11-21'),
(1234,598701,45.2,'2004-10-01'),
(1234,567890,66.5,'2004-9-21'),
(3456,789065,22.5,'2004-10-01'),
(3456,789065,77.5,'2004-10-27'),
(3456,678901,48.5,'2004-12-21');

 

Sql:

select NO,NO2,
     sum(case  when itime like '2004-%9%' then num else 0 end) as 9M,
     sum(case  when itime like '2004-10%' then num else 0 end) as 10M,
     sum(case  when itime like '2004-11%' then num else 0 end) as 11M,
    sum(case  when itime like '2004-12%' then num else 0 end) as 12M
    from table_a group by no,no2 order by no,no2 ;

 

结果:

+------+--------+------+------+------+------+

| NO   | NO2    | 9M   | 10M  | 11M  | 12M  |

+------+--------+------+------+------+------+

| 1234 | 567890 | 66.5 |    0 |    0 | 33.5 |

| 1234 | 598701 |    0 | 45.2 | 44.8 |    0 |

| 3456 | 678901 |    0 |    0 |    0 | 48.5 |

| 3456 | 789065 |    0 |  100 |    0 |    0 |

+------+--------+------+------+------+------+

 

 

 

 

你可能感兴趣的:(sql,面试)