日期:2014-05-17  浏览次数:20776 次

关于一个SQL语句group by的实现
表 table01
字段 add_time, mat_name, mat_wt
  20110301005010 石灰 100
  20110301075910 轻烧镁球 180
  20110301121426 石灰 200
  20110302191826 萤石 120
  20110303052345 轻烧镁球 60
  20110303060930 萤石 160

表 table02
字段 create_time, prod_shift_group
  20110301000413 丙
  ... 丙
  20110301075901 丙
  20110301080308 丁
  ... 丁
  20110301155655 丁
  20110301160336 甲
  ....
  20110301235942 甲
  20110302000347 丙
  ...
  20110302075848 丙
  20110302080452 丁
  ... 丁
  20110302155534 丁
  20110302160243 甲
  ... 甲
  20110302185932 甲
  20110303024443 乙
  ... 乙
  20110303074642 乙

现在我想在table01表里面根据日期号, mat_name, 还有prod_shift_group来求得sum(mat_wt)。
我只会写:
select mat_name, substr(add_time, 7, 2), sum(mat_wt)
from table01
where add_time > '20110301005010'
and add_time < '20110303060930'
group by mat_name, substr(add_time, 7, 2)
就是不会关联table02里面的班组。

------解决方案--------------------
SQL code
--这两个表是通过add_time和create_time进行关联吗?
select mat_name,prod_shift_group,substr(add_time, 7, 2), sum(mat_wt)
from table01,table02
where table01.add_time=table02.create_tiem 
      add_time > '20110301005010'
      and add_time < '20110303060930'
group by mat_name,prod_shift_group,substr(add_time, 7, 2)

------解决方案--------------------
SQL code
select mat_name,prod_shift_group,substr(add_time, 7, 2), sum(mat_wt)
from table01,table02
where table01.add_time=table02.create_tiem 
      add_time > '20110301005010'
      and add_time < '20110303060930'
group by mat_name,prod_shift_group,substr(add_time, 7, 2)

------解决方案--------------------
SQL code
select mat_name,prod_shift_group,to_char(add_time,'yyyymmdd'), sum(mat_wt)
from table01,table02
where table01.add_time=table02.create_tiem 
      add_time > '20110301005010'
      and add_time < '20110303060930'
group by mat_name,prod_shift_group,to_char(add_time,'yyyymmdd')