我需要每个月获得一件商品的总数。
到目前为止,使用以下代码:
Select Count(mpay_collector_company.id) As `Number of Collector Companies`,
Month(mpay_collector_company.created_at) As Month,
Year(mpay_collector_company.created_at) As Year
From mpay_collector_company
Group By Month(mpay_collector_company.created_at),
Year(mpay_collector_company.created_at)
我有以下回应:
#|Year|Month
------------
5|2014|11
3|2014|12
3|2015|1
7|2015|2
6|2015|3
2|2015|4
5|2015|6
1|2015|7
而不是每个月的数字,我想从每个月的开头得到总和,这将是这样的:
Sum|Year|Month
--------------
5|2014|11
8|2014|12
11|2015|1
18|2015|2
24|2015|3
26|2015|4
31|2015|6
32|2015|7
有什么想法吗?
编辑:此请求将作为一个视图实现,因此子请求几乎是不可行的:x
答案 0 :(得分:0)
您可以先选择不同的year.months,然后检查每个值的计数
select year,month ,
( SELECT count(*) FROM mpay_collector_company WHERE
Year(mpay_collector_company.created_at) <= temp1.year
AND
Month(mpay_collector_company.created_at) <= temp1.month
)
from (
Select DISTINCT
Month(mpay_collector_company.created_at) As month,
Year(mpay_collector_company.created_at) As year
From mpay_collector_company
) as temp1
ORDER BY year,month
如果你想&#34;重置&#34;对于每一年,只需将年份之间的比较改为EQUAL即可
select year,month ,
( SELECT count(*) FROM mpay_collector_company WHERE
Year(mpay_collector_company.created_at) = temp1.year
AND
Month(mpay_collector_company.created_at) <= temp1.month
)
from (
Select DISTINCT
Month(mpay_collector_company.created_at) As month,
Year(mpay_collector_company.created_at) As year
From mpay_collector_company
) as temp1
ORDER BY year,month
答案 1 :(得分:0)
使用相关子查询来计算当前应该也可以使用日期的行数:
Select
Count(id) As "Number of Collector Companies",
Month(created_at) As Month,
Year(created_at) As Year,
(
Select Count(*)
From mpay_collector_company
Where EXTRACT(YEAR_MONTH from created_at) <= EXTRACT(YEAR_MONTH from m.created_at)
) as running_count
From mpay_collector_company m
Group By Year(created_at), Month(created_at);
Sample SQL Fiddle在行动中显示
答案 2 :(得分:0)
这样的事情可行:
Select Count(distinct previous_mpay_collector_company.id)+ Count(distinct mpay_collector_company.id) As `Number of Collector Companies`,
Month(mpay_collector_company.created_at) As Month,
Year(mpay_collector_company.created_at) As Year
From mpay_collector_company
Left Join mpay_collector_company previous_mpay_collector_company
On Year(mpay_collector_company.created_at) > Year(previous_mpay_collector_company.created_at)
OR (Month(mpay_collector_company.created_at) > Month(previous_mpay_collector_company.created_at)
And Year(mpay_collector_company.created_at) >= Year(previous_mpay_collector_company.created_at))
And previous_mpay_collector_company.id <> mpay_collector_company.id
Group By Month(mpay_collector_company.created_at),
Year(mpay_collector_company.created_at);
诀窍是自我加入前几个月并从联合表中算起。
答案 3 :(得分:0)
Select
(Select Sum(Count(Z.id)) FROM mpay_collector_company z
where z.created_at <= A.created_at) as '#',
Month(A.created_at) As Month,
Year(A.created_at) As Year
From mpay_collector_company A
Group By Month(mpay_collector_company.created_at),
Year(mpay_collector_company.created_at)
这应该为你做,