MySQL:计算两个日期列并按日计算

时间:2016-10-19 19:51:13

标签: mysql

我需要绘制折线图,​​以便在某些日期之间显示每天的订单和取件。订单和取件日期存储在unixtime中。我的表看起来像这样:

id    order_date    pickup_date
-------------------------------
1     1472749664     1472133376
2     1472551372     1472567548
3     1472652545     1472901368
4     1473154659     1473512323
5     1473512923     1475229824
6     1475586643     1475652635

我所追求的是这样的事情

date        orders    pickups
-------------------------------
01-09-2016  1         0
02-09-2016  4         1
03-09-2016  3         2
04-09-2016  7         1
05-09-2016  0         0
06-09-2016  1         1
07-09-2016  6         3
08-09-2016  0         0
08-09-2016  3         5
10-09-2016  2         4

我知道我可以根据一栏来计算,例如:

SELECT
    COUNT(id) AS orders,
    FROM_UNIXTIME(order_dates, '%d-%m-%Y') AS date
FROM orders
GROUP BY request_date

但我不知道如何计算两列并将它们分组为每天。

1 个答案:

答案 0 :(得分:0)

你可以使用这样的查询:

SELECT sum(orders) as orders, sum(pickups) as pickups, date
FROM (
SELECT
    COUNT(id) AS orders, 0 as pickups,
    FROM_UNIXTIME(`order_date`, '%d-%m-%Y') AS date
FROM orders
GROUP BY order_date
UNION
SELECT
    0 AS orders, COUNT(id) as pickups,
    FROM_UNIXTIME(`pickup_date`, '%d-%m-%Y') AS date
FROM orders
GROUP BY pickup_date ) ut
GROUP BY date

Here是一个小提琴。