简体   繁体   中英

Get SUM of 1st column ON DISTINCT 2nd column

I need to get the sales total from our table for a certain date range, and display the results grouped by day of the week. (making a chart)

The following is what i have so far

SELECT  DAYNAME(sale_date), SUM(total_price + total_tax)
        FROM threewor_vend.vendsales AS s
        WHERE s.register_id = '07709f8e-8d90-11e0-8e09-4040f540b50a'
        AND sale_date >= DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY)
        GROUP BY  DAYOFWEEK(sale_date)

This returns the day and total sales for each day, which is great.

Thing is, there are multiple rows 'per sale' if there is more than one item per sale. So the total price is duplicated a number of times. So i can't just get the sum of total_price.

I need to get the sum of the total_price, ONLY for each UNIQUE sale_id.

eg

sale id | item | itemqty | item value | item total | total_price |
---1----|-drum-|-1-------|-60.00------|-60.0-------|-$230.00-----|
---1----|-uke--|-1-------|-170.00-----|-170.0------|-$230.00-----|  

In MySQL, you can group by the sale_id . This will eliminate the duplicates:

    SELECT  DAYNAME(sale_date), SUM(total_price + total_tax)
    FROM (select s.*
          from threewor_vend.vendsales s
          group by sale_id
         ) s
    WHERE s.register_id = '07709f8e-8d90-11e0-8e09-4040f540b50a'
    AND sale_date >= DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY)
    GROUP BY  DAYOFWEEK(sale_date);

As long as the other columns -- sale_date , total_price , total_tax , and register_id -- are the same on all the rows for a given sale_id , then this will work.

Since you're storing the total_price multiple times per sale, your results are being multiplied.

Here's one option using a subquery with DISTINCT assuming the four fields are all the same for each duplicated sale:

SELECT DAYNAME(sale_date), SUM(total_price + total_tax)
FROM (
    SELECT DISTINCT sale_date, total_price, total_tax, register_id
    FROM threewor_vend.vendsales 
    WHERE s.register_id = '07709f8e-8d90-11e0-8e09-4040f540b50a'
        AND sale_date >= DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY)
) t
GROUP BY DAYOFWEEK(sale_date)

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