select x.商品Id,a.名称,sum(case when mytype=1 then x.数量 else 0 end) as 出库数量,sum(case when mytype=0 then x.数量 else 0 end) as 入库数量,sum(case when mytype=0 then x.数量 else -1*x.数量 end) as 库存 ( (select 0 as mytype,商品Id,数量 from 入库表 where 某一个时间点 ) b union (select 1 as mytype,商品Id,数量 from 出库表 where 某一个时间点) c ) x inner join 商品资料表 a on a.商品Id=x.商品Id grouo by x.商品Id
select x.商品Id,a.名称,sum(case when mytype=1 then x.数量 else 0 end) as 出库数量,sum(case when mytype=0 then x.数量 else 0 end) as 入库数量,sum(case when mytype=0 then x.数量 else -1*x.数量 end) as 库存 from --加此字段。 ( (select 0 as mytype,商品Id,数量 from 入库表 where 某一个时间点 ) b union all --加上一个all字段,防止有重复的记录漏掉 (select 1 as mytype,商品Id,数量 from 出库表 where 某一个时间点) c ) x inner join 商品资料表 a on a.商品Id=x.商品Id grouo by x.商品Id
感谢楼上的提点,已经查询出来了,但有一事,还需请教一下。select x.商品Id,a.名称,sum(case when mytype=1 then x.数量 else 0 end) as 出库数量,sum(case when mytype=0 then x.数量 else 0 end) as 入库数量,sum(case when mytype=0 then x.数量 else -1*x.数量 end) as 库存 from --加此字段。 ( (select 0 as mytype,商品Id,数量 from 入库表 where 某一个时间点 ) b ** union all --加上一个all字段,防止有重复的记录漏掉 (select 1 as mytype,商品Id,数量 from 出库表 where 某一个时间点) c ** ) x inner join 商品资料表 a on a.商品Id=x.商品Id grouo by x.商品Id *** 带**号的行中,必须要吧b,c去掉才可以正常查询,否则会报UNION附近存在语法错误。是怎么回事?
(
(select 0 as mytype,商品Id,数量 from 入库表 where 某一个时间点 ) b
union
(select 1 as mytype,商品Id,数量 from 出库表 where 某一个时间点) c
) x
inner join 商品资料表 a on a.商品Id=x.商品Id
grouo by x.商品Id
*****************************************************************************
欢迎使用CSDN论坛专用阅读器 : CSDN Reader(附全部源代码) http://feiyun0112.cnblogs.com/
包含大致的字段有ID,商品ID,库存数量,最近入库时间,最近出库时间。
每次入库时,更新库存数量+=入库数量,同时更新最近入库时间字段。
每次出库时,更新库存数量-=入库数量,同时更新最近出库时间字段。
from --加此字段。
(
(select 0 as mytype,商品Id,数量 from 入库表 where 某一个时间点 ) b
union all --加上一个all字段,防止有重复的记录漏掉
(select 1 as mytype,商品Id,数量 from 出库表 where 某一个时间点) c
) x
inner join 商品资料表 a on a.商品Id=x.商品Id
grouo by x.商品Id
from --加此字段。
(
(select 0 as mytype,商品Id,数量 from 入库表 where 某一个时间点 ) b **
union all --加上一个all字段,防止有重复的记录漏掉
(select 1 as mytype,商品Id,数量 from 出库表 where 某一个时间点) c **
) x
inner join 商品资料表 a on a.商品Id=x.商品Id
grouo by x.商品Id ***
带**号的行中,必须要吧b,c去掉才可以正常查询,否则会报UNION附近存在语法错误。是怎么回事?