我有一张产品销售表
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
您能以高效优雅的方式帮助实现这一目标吗?
答案 0 :(得分:3)
做你想做的事有点挑战,因为这些组重叠。你有两个选择。第一个是进行条件聚合并将结果放在列中:
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;
要在单独的行上获得结果,您可以转动此结果。或者,您可以直接进行计算。为此,您需要构建一个描述组的表:
[注意:Stack Overflow不允许我在此答案中包含我的最终查询。它在评论中。]
编辑:由于戈登无法发表答案,我会这样做。 (我希望这对你戈登没问题。)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;
答案 1 :(得分:0)
SELECT 'GROUP 1' AS `Group`, SUM(price_sold) AS PriceSum
FROM MyTable
WHERE product_id = 1 OR product_id = 2
UNION
SELECT 'GROUP 2', SUM(price_sold)
FROM MyTable
WHERE product_id = 2 OR product_id = 3
结果如下: