日期:2014-05-17 浏览次数:20566 次
create table Goods
(GoodsId int, StartDate date)
insert into Goods
select 1, '2013-5-1' union all
select 2, '2013-4-1' union all
select 3, '2013-6-3'
create table OrderGoods
(GoodsNumber int, GoodsId int, OrderId int)
insert into OrderGoods
select 1, 1, 1 union all
select 2, 2, 1 union all
select 1, 3, 1 union all
select 2, 3, 2 union all
select 1, 1, 2 union all
select 5, 2, 3 union all
select 1, 3, 4
create table OrderInfo
(OrderId int, AddTime date)
insert into OrderInfo
select 1, '2013-5-3' union all
select 2, '2013-5-5' union all
select 3, '2013-5-8' union all
select 4, '2013-6-9'
select a.GoodsId,
sum(case when b.AddTime>c.StartDate then a.GoodsNumber
else 0 end) 'GoodsNumber'
from OrderGoods a
inner join OrderInfo b on a.OrderId=b.OrderId
inner join Goods c on a.GoodsId=c.GoodsId
group by a.GoodsId
/*
GoodsId GoodsNumber
----------- -----------
1 2
2 7
3 1
(3 row(s) affected)
*/