MYSQL - 在连接两个表之后按日期时间排序

时间:2015-02-26 13:17:44

标签: mysql datetime

感谢您查看我的问题。

我试图通过mysql将dateotal列和group by datetime相加。在总和之前,我必须加入两个表。

我的第一张表Payments包含以下数据:

ID | User_ID | Order_ID | Subtotal | Tax | Tip | Discount | Total | Payment_Method | Payment_Collected
12 | 123     |    76    | 10.99    | 0.99|  1  | 0.00     | 12.98 | Cash           |    1

我的第二张表Order包含以下数据:

ID | User_ID | Address_ID |    orderplaced_ts    | order_status
76 |   23    |     123    | 2015-02-26 12:23:41  | 

我尝试运行的查询如下:

select `order`.orderplaced_ts, SUM(`payments`.subtotal) as Subtotal
from `payments`
join `order` on `order`.id=`payments`.order_id
where `order`.order_status != "Cancelled"
and `payments`.payment_collected = 1
group by `order`.orderplaced_ts

我想要实现的是获得所有小计的所有总和并按相同的日期时间分组。样本输出将是:

orderplaced_ts   |  Subtotal
 2015-02-20      |   123.12
 2015-02-21      |   223.12
 2015-02-22      |   124.25
 2015-02-23      |   247.23
 2015-02-24      |   623.50

我当前的查询输出是:

 orderplaced_ts       |  Subtotal
 2015-02-20 05:56:23  |   123.12
 2015-02-20 06:36:23  |   123.12
 2015-02-20 06:38:23  |   123.12

有人可以指出我正确的方向,为什么我的查询没有给我所需的输出?

1 个答案:

答案 0 :(得分:1)

您需要使用格式化日期来摆脱时间。 我认为这会做你想要的(未测试):

select date_format(`order`.orderplaced_ts,"%Y-%m-%d"), SUM(`payments`.subtotal) as Subtotal
from `payments`
join `order` on `order`.id=`payments`.order_id
where `order`.order_status != "Cancelled"
and `payments`.payment_collected = 1
group by date_format(`order`.orderplaced_ts,"%Y-%m-%d")