根据时间戳列中的日期部分计算行数

时间:2017-09-20 15:37:24

标签: mysql

我有一个表food_orders,其中包含以下架构:

ID    created_at
=========================
1   2017-08-31 20:49:47
2   2017-09-20 21:07:52
3   2017-09-23 21:07:52
4   2017-09-23 20:07:52

我需要计算过去10天内每天订单的数量。 我需要这样的东西:

Date           no_orders
=========================
2017-08-31      1
2017-09-20      1
2017-09-23      2

我试过了:

SELECT created_at, COUNT('id') AS qty  FROM orders WHERE created_at > (CURDATE() - INTERVAL 10 DAY) group by created_at

当然给了我no_orders 1的所有记录 请帮帮我们!

2 个答案:

答案 0 :(得分:2)

我认为你只需要一个简单的聚合查询。这里唯一需要注意的是,您的created_at列是一个时间戳,因此我们需要将其投放到某个日期,以强制某一天的所有时间都在同一天。

SELECT
    DATE(created_at) AS Date,
    COUNT(*) AS no_orders
FROM yourTable
WHERE
    created_at >= CURDATE() - INTERVAL 10 DAY
GROUP BY
    DATE(created_at)

答案 1 :(得分:1)

SELECT CAST(created_at AS DATE) AS createdDay, COUNT('id') AS qty  
FROM orders 
WHERE created_at > (CURDATE() - INTERVAL 80 DAY) 
group by CAST(created_at AS DATE)

demo

结果:

| createdDay | qty |
|------------|-----|
| 2017-08-31 |   1 |
| 2017-09-20 |   1 |
| 2017-09-23 |   2 |