我有一个以下结构的mysql表。
orders ( id, order_status(number), date(timestamp));
状态更改时更新日期。
使用order_status
选择所有订单的计数。
但是,应根据日期选择一个order_status
表示状态ID为10。
例如:考虑状态ID 10表示订单已完成。选择状态为10的订单计数,该订单今天更新。并且所有其他状态计数都没有任何条件。
count | s
------+---
2 | 1
6 | 2
8391 | 10
5 | 7
6 | 15
28 | 18
答案 0 :(得分:2)
修改查询我添加了日期条件:
select
sum(1) all_orders
, sum(case when order_status <> 10 then 1 else 0 end) as unclosed_orders
, sum(case when order_status = 10 AND date=DATE_FORMAT(NOW(),'%Y-%m-%d') then 1 else 0 end) as closed_orders_today
, sum(case when order_status = 10 AND date!=DATE_FORMAT(NOW(),'%Y-%m-%d')then 1 else 0 end) as closed_orders_past
from orders
希望这有帮助!
修改强>
两个查询的联合可能获得您想要的输出:
SELECT COUNT(*) as count, order_status as s FROM orders WHERE order_status='10' AND date=DATE_FORMAT(NOW(),'%Y-%m-%d')
UNION
SELECT COUNT(*) as count, order_status as s FROM orders WHERE order_status!='10' GROUP BY order_status
1)查询返回状态为10的计数,并于今天放置。
2)查询返回状态不是10的计数。
两者的联合返回计数和状态以获得所需的输出。
答案 1 :(得分:0)
使用&#34; 有条件聚合&#34;在case expressions
内aggregate function
例如:
select count(*) all_orders , count(case when order_status 10 then id end) as unclosed_orders , count(case when order_status = 10 then id end) as closed_orders , count(case when order_status = 10 and last_updated_date = current_date() then id end) as closed_today from your_table
注意:COUNT()
函数会忽略NULL
s
您可以使用SUM()
来模拟相同的结果,例如:
select
sum(1) all_orders
, sum(case when order_status <> 10 then 1 else 0 end) as unclosed_orders
, sum(case when order_status = 10 then 1 else 0 end) as closed_orders
from your_table
但是,如果这是数字代表的话,我宁愿使用COUNT()
。