我的数据库中有一些数据:
Item date qty
gum 2012-03-13 1
soap 2012-03-12 3
soap 2012-03-11 10
candy 2012-03-04 20
sugar 2012-03-01 2
我想如果我为soap选择数据,我会得到如下数据:
Item date qty
soap 2012-03-12 35 (counting all data until max(date) of soap)
(even soap is have twice input but get the max(date))
我只是有一个问题:
SELECT Item,MAX(date) FROM list WHERE Item LIKE 'soap'
如何放COUNT(qty)
,所以我会得到上面的结果?
答案 0 :(得分:2)
看起来你的例子是错的。它应该导致33
不在35
,因为糖来自年2013
。知道:)这是查询:
select item, max(date) MaxDate,
(select sum(qty) from t t1
where t1.date <= (select max(date) from t
where item = 'soap')
) as totalQty
from t t2
where item = 'soap'
group by item
或许,如果你不喜欢看两次'肥皂',那么这也应该有效:
select item, max(date) MaxDate,
(select sum(qty) from t t1
where t1.date <= (select max(date) from t
where item = @item)
) as totalQty
from t t2, (select @item := 'soap') init
where item = @item
group by item
答案 1 :(得分:0)
SELECT Item, MAX(date), SUM(qty)
FROM list
WHERE Item = 'soap'
GROUP BY Item