王琳丢包:SQL 数个表中相同ID的求和查询

来源:百度文库 编辑:杭州交通信息网 时间:2024/05/01 03:54:41
有数个表(表名以日期命名):20060801、20060802、20060803、20060804……
每个表里内容:ID、销售额、日期……

用SQL查询 某个时间段 某单品的销售和,如:求ID为123在20060801至20060804期间的销售总和。怎么写呢?

注:期间某天此商品可能无销售,那么那天的表里就无此商品的ID。
如:20060803那天123无销售,表20060803里ID就没有123

求ID为123在20060801至20060804期间的销售总和:
select id,sum(销售额)
from (
select *from 20060801
Union
select *from 20060802
Union
select *from 20060803
Union
select *from 20060804
)
where id=123
group by id

select id,sum(销售额)
from (
select *from 20060801 where id=123
Union
select *from 20060802 where id=123
Union
select *from 20060803 where id=123
Union
select *from 20060804 where id=123
)
group by id

如果表的数量都不能确定,那么就不是一件易事了
一两句SQL解决不了问题