我有一个像这样的表:orders(id,created_ts,status) 我想生成一个MySQL查询,该查询显示created_ts未结订单的数量。 created_ts是MySQL时间戳
样本数据:
id created_ts status
--- ---------- -------
1 11-1-2017 Open
2 11-1-2017 Open
3 12-1-2017 Open
4 13-1-2017 Open
5 13-1-2017 Closed
6 14-1-2017 Closed
Outpur:
created_ts count
-------- ------
11-1-2017 2
12-1-2017 3
13-1-2017 4
14-1-2017 4
计数是该日期的未结订单数。
计算方法如下。
日期中的订单数=状态为“未清”且该行的created_ts <= created_ts的所有订单。
我不知道如何解决这个问题。 谁能帮我。
答案 0 :(得分:2)
您可以使用相关查询来获取不同日期的未结订单的运行总数
select t1.created_ts,
(select count(*)
from demo
where created_ts <=t1.created_ts
and status = 'Open') date_wise_sum
from (
select distinct created_ts
from demo
) t1
答案 1 :(得分:1)
似乎您需要累计金额:
SELECT t.created_ts,
(@running_total := @running_total + count(case when status='Open'then t.id else null end)) AS countval
FROM TABLE t
JOIN (SELECT @running_total := 0) r
group by t.created_ts
ORDER BY t.created_ts
答案 2 :(得分:1)
如果我理解正确,我们将仅查看打开的记录,而忽略关闭的记录。您希望使用Windows函数获得的运行总计,该功能自MySQL 8起可用:
select created_ts, sum(sum(status = 'Open')) over (order by created_ts) as cnt
from mytable
group by created_ts
order by created_ts;
例如,在早期版本中,您可以将计数与日期相加:
select dates.created_ts, sum(counted.cnt) as total
from
(
select distinct created_ts
from mytable
) dates
join
(
select created_ts, count(*) as cnt
from mytable
where status = 'Open'
group by created_ts
) counted on counted.created_ts <= dates.created_ts
group by dates.created_ts
order by dates.created_ts;