Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 从当前数据为最长日期的数据库中统计数据_Mysql_Select_Count - Fatal编程技术网

Mysql 从当前数据为最长日期的数据库中统计数据

Mysql 从当前数据为最长日期的数据库中统计数据,mysql,select,count,Mysql,Select,Count,我的数据库中有一些数据: 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-1

我的数据库中有一些数据:

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'

如何放置COUNTqty,这样我将得到上面的结果?

看起来您的示例是错误的。这将导致33而不是35,因为糖是从2013年开始的。明白了:以下是查询:

SELECT Item, MAX(date), SUM(qty) 
FROM list 
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 = '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

您想按item='soap'进行筛选,但您想在不进行此筛选的情况下对数量求和?@BenRowe:我已经编辑了我的帖子,我想统计数据,直到soap的最长日期。@nunu:那么您想要soap的最长日期,但表中所有数量的总和在一行?@MostyMostacho:我已经编辑了我的帖子。这使我得到的数量=36。我必须停止计算肥皂的最大日期。这意味着我必须得到数量=35。我把你的问题搞错了,我以为你只想计算肥皂的数量。33对35的数据很好,但我确信这只是一个o型。。。你可能也期望如此,但无论如何都是正确的。它是在soap的maxdate之前计算所有数据,我可以过滤它只是在当前月份计算。事实上,我有这么多行数据。