`
zeyuphoenix
  • 浏览: 56009 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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 |

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

 

 

 

 

分享到:
评论
发表评论

文章已被作者锁定,不允许评论。

相关推荐

Global site tag (gtag.js) - Google Analytics