简体   繁体   English

SQL - 按 ID 的基数分组

[英]SQL - Group by the base of an ID

My SQL is not really good, but I am improving.我的 SQL 不是很好,但我正在改进。

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. retailer_id是从 5 位数字的根和(如果存在子公司)两个数字的相邻 _ 构建的。 Like so:像这样:

  • without subsidiaries: 30000无子公司:30000
  • with subsidiaries: 30000_01, 30000_02与子公司: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零售商 ID month grand total累计
10006 10006 12 12 10 10
10006 10006 9 9 20 20
10006 10006 9 9 40 40
10006_10 10006_10 12 12 40 40
10015 10015 9 9 10 10
10015 10015 11 11 10 10
10015 10015 12 12 5 5
10015 10015 11 11 20 20

expected result:预期结果:

retailer_id零售商 ID month Totals总计
10006 10006 12 12 50 50
10006 10006 9 9 60 60
10015 10015 9 9 10 10
10015 10015 11 11 30 30
10015 10015 12 12 5 5
10015 10015 11 11 20 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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