简体   繁体   中英

SQL - Group by the base of an ID

My SQL is not really good, but I am improving.

I try to extract records from a table with sales data. I want to know how much profit was made by a retailer and its subsidiaries per month.

The retailer_id is build from the root of 5 digits and (if subsidiaries exist) an adjacent _ with two digits. Like so:

  • without subsidiaries: 30000
  • with subsidiaries: 30000_01, 30000_02

Code:

SELECT
    retailer_id,
    MONTH(Date(created_at)) AS month,
    SUM(grand_total) AS Totals
FROM 
    sales_table
GROUP BY 
    retailer_id, month

As you can imagine, the retailer with subsidiaries are still separated line items.

As requested, I will give an example:

raw data

retailer_id month grand total
10006 12 10
10006 9 20
10006 9 40
10006_10 12 40
10015 9 10
10015 11 10
10015 12 5
10015 11 20

expected result:

retailer_id month Totals
10006 12 50
10006 9 60
10015 9 10
10015 11 30
10015 12 5
10015 11 20

Thank you for your help!

The answer is 'left'. As in this one:

select 
 left(retailer_id, 5),
 Month(Date(created_at)) AS month,
 sum(grand_total) AS Umsatz
FROM sales_order
WHERE store_id = '2' AND NOT status = 'canceled' AND created_at between '2021-09-01' AND '2022-01-27'
GROUP BY left(retailer_id, 5), month
ORDER BY left(retailer_id,5);

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