mysql - 按不同的键子集分组

标签 mysql sql

我有一张产品销售表

id  product_id  price_sold
1      1            500
2      1            300
3      2            100
4      3            200
5      3            100

我希望能够对不同产品子集的价格求和,比如:每组产品 1,2 的价格总和。以及每组产品 2,3 的价格总和的另一个计算,因此所需的结果将是:

group 1, 900
group 2, 400

您能以高效而优雅的方式帮助您做到这一点吗?

最佳答案

做你想做的事情有点挑战,因为小组重叠。你有两个选择。首先是做条件聚合,把结果放在列中:

select sum(case when product_id in (1, 2) then price_sold end) as group1,
       sum(case when product_id in (2, 3) then price_sold end) as group2
from productsales ps;

要获得不同行的结果,您可以旋转该结果。或者,您可以直接进行计算。为此,您需要构建一个描述组的表:

select pg.grpid, sum(ps.price_sold)
from productsales ps
join
(
  select 1 as grpid, 1 as product_id
  union all
  select 1 as grpid, 2 as product_id
  union all
  select 2 as grpid, 2 as product_id
  union all
  select 2 as grpid, 3 as product_id
) pg on ps.product_id = pg.product_id
group by pg.grpid;

关于mysql - 按不同的键子集分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24610859/

相关文章:

sql - 优化一条Sql查询: filter an unindexed field

SQL:军事时间转换后在 AM/PM 之前添加空格

sql - 有没有办法在 postgres 中存储预先排序的行?

c# - 什么是最佳选择,Windows 窗体或 C# 中的 WPF 开发?

php - Laravel 复杂的内部加入多对多关系

php - 保存简单的复选框 bool 值 php

php - GROUP_CONCAT 奇怪的结果

php - 将多个查询数据放入单个 HTML 表(PHP、MySQL)

mysql - 将数据保存为数组还是多行?哪种方式更有效率?

mysql - 选择两列不等于 0 的计数