我不知道怎样才能在一栏中得到某一年(2001年)以来的总金额。
我有这张桌子
ID | date
==========
1 | 2001
2 | 2001
3 | 2002
4 | 2003
5 | 2003
7 | 2003
8 | 2004
9 | 2004
10 | 2006我喜欢得到:
date | count | total
====================
2001 | 2 | 2
2002 | 1 | 3
2003 | 3 | 6
2004 | 2 | 8
2005 | 0 | 8
2006 | 1 | 9从根本上说,2001年是本年度的2次,总共是2次;2002年是本年度的1次,2001年是3次;2003年是本年度的3次,2001年和2002年的/from年是6次),等等。
发布于 2014-02-16 15:49:56
您似乎需要total列中的累积和。下面是一种使用关联子查询来完成此操作的方法:
select date, count(*) as `count`,
(select count(*) from table t2 where t2.date <= t.date) as total
from table t
where date > 2000
group by date;编辑:
如果您想要所有的日期,那么您需要生成它们并加入它们:
select dates.date, count(*) as `count`,
(select count(*) from table t2 where t2.date <= dates.date) as total
from (select 2001 as date union all
select 2002 union all
select 2003 union all
select 2004 union all
select 2005 union all
select 2006
) dates left outer join
table t
on dates.date = t.date
where t.date > 2000
group by dates.date;https://stackoverflow.com/questions/21813356
复制相似问题