简体   繁体   中英

Difference between dates with one date column in mysql

i have the below query:

SELECT transaction_date,tanks.name,stations.name,products.name,tank_sales 
FROM tanks_product_movement LEFT JOIN stations ON station_id=stations.id 
LEFT JOIN products ON product_id=products.id LEFT JOIN tanks ON 
tank_id=tanks.id WHERE products.name='AGO'
AND stations.name='CG-Station'

i want to know the difference in sales between two days ie sales difference between 2019-04-01 and 2019-04-02?

enter image description here

Assuming these two dates would occur only once in the respective table, you could use pivoting logic here:

SELECT
    MAX(CASE WHEN transaction_date = '2019-04-02' THEN tank_sales END) -
    MAX(CASE WHEN transaction_date = '2019-04-01' THEN tank_sales END) AS sales_diff
FROM tanks_product_movement tpm
LEFT JOIN stations s
    ON tpm.station_id = s.id 
LEFT JOIN products p
    ON tpm.products_id = p.id
LEFT JOIN tanks t
    ON tank_id = t.id
WHERE
    p.name = 'AGO' AND
    s.name = 'CG-Station';

To find the difference between today and yesterday's sales use:

SELECT
    MAX(CASE WHEN transaction_date = CURDATE() THEN tank_sales END) -
    MAX(CASE WHEN transaction_date = SUBDATE(CURDATE(), 1) THEN tank_sales END)

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