我在MySQL中有一个表,我想按操作分组。这是我的桌子
预期结果应该是按bag_no分组的价格总和,但product_id应该是mainproduct ='Y'。所以结果应该是这样
我可以执行以下操作
SELECT bag_no, sum(price) AS total_price
FROM myTable
GROUP BY bag_no
但是,这不允许我在我也想要的表中添加product_id。我们该怎么做?
答案 0 :(得分:2)
执行此操作的一种规范方法涉及加入子查询以查找总和:
SELECT
t1.bag_no,
t1.product_id,
t2.total_price
FROM myTable t1
INNER JOIN
(
SELECT bag_no, SUM(price) AS total_price
FROM myTable
GROUP BY bag_no
) t2
ON t1.bag_no = t2.bag_no
WHERE
t1.mainproduct = 'Y';
使用支持分析功能的MySQL 8+,我们可以稍微简化上述查询:
WITH cte AS (
SELECT
t1.bag_no,
t1.product_id,
SUM(price) OVER (PARTITION BY t1.bag_no) total_price,
t1.mainproduct
FROM myTable t1
)
SELECT bag_no, product_id, total_price
FROM cte
WHERE mainproduct = 'Y';