简体   繁体   中英

MYSQL - Sum Rows by datetime after joining two tables

Thank you for looking at my question.

I am trying to sum the subtotal column and group by datetime via mysql. I have to join two tables, prior to the sum.

My first table, Payments, contains the following data:

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

My second table, Order, contains the following data:

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

The query that I tried to run is as follows:

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

What I'm trying to achieve is to get all the sum of all subtotals and grouped by the same datetime. Sample output would be:

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

My current query output is:

 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

Can someone please point me in the right direction of why my query isn't giving me the desired output?

You need to use a formatted date to get rid of the time. I think this would do what you want (not tested):

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM