基于SQL中的一列的聚集行
我有一个看起来像这样的数据集:
report_id | category_id | product_id | year_month | total_sales |
---|---|---|---|---|
10 | a | 1 | 202201 | 10 |
10 | A | 1 | 202202 | 16 |
10 | A | 2 | 202201 | 11 |
10 | A | 3 | 202201 | 8 |
10 | A | 4 | 10 A 4 202202 | 202201 12 |
10 | A | 4 | 202202 | 202202 15 |
10 | B | 7 | 19 192202 19 192202 19 192202 | 19 |
10 | B | 8 | 202204 | 17 |
10 | B | 9 | 202203 | 9 |
我试图汇总该表,如果category_id = a没有任何category_id = b; aCTORY_ID = A的所有产品都可以称为“ MISC”。
所需的数据集应该看起来像:
report_id | category_id | product_id | year_month | total_sales_sales |
---|---|---|---|---|
10 | a | misc | 202201 | 41 |
10 | a | misc | 202202 | 31 |
10 | B | 7 | 202202 | 19 |
10 | B | 8 | 202204 | 17 |
10 | B | 9 | 202203 | 9 |
我完全丢失了如何生产此数据的数据放。
感谢您的帮助
I have a data set that looks like this:
report_id | category_id | product_id | year_month | total_sales |
---|---|---|---|---|
10 | A | 1 | 202201 | 10 |
10 | A | 1 | 202202 | 16 |
10 | A | 2 | 202201 | 11 |
10 | A | 3 | 202201 | 8 |
10 | A | 4 | 202201 | 12 |
10 | A | 4 | 202202 | 15 |
10 | B | 7 | 202202 | 19 |
10 | B | 8 | 202204 | 17 |
10 | B | 9 | 202203 | 9 |
I am trying to summarize the table where I can aggregate by year_month if category_id = A without any aggregation for category_id = B; all products for category_id = A can be referred to as 'misc'.
The desired data set should look like this:
report_id | category_id | product_id | year_month | total_sales |
---|---|---|---|---|
10 | A | misc | 202201 | 41 |
10 | A | misc | 202202 | 31 |
10 | B | 7 | 202202 | 19 |
10 | B | 8 | 202204 | 17 |
10 | B | 9 | 202203 | 9 |
I am totally lost as to how to produce this data set.
Thanks for your help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以汇总:
group_concat
以条件方式使用如果
函数检查demo 在这里。
注意:这是一个通用的解决方案,如果您的“杂项”值应在任何类别中找到,而不是根据您的特定示例数据找到唯一的“ A”类别。
You can aggregate over:
GROUP_CONCAT
in a conditional way using theIF
functionCheck the demo here.
Note: this is a generalized solution, in case your 'misc' value should ever be found in any category, rather than the only category 'A', as per your specific sample data.
我们可以使用案例根据category_id中的值将列product_id格式化,然后按结果进行分组。
db<>>
We can use case to format the column product_id according to the value in category_id and then group by the result.
db<>fiddle here