Reputation: 5021
I have a table in MySQL and I want to do some group by operation. So here is my table
The expected result should be the sum of prices group by bag_no but the product_id should be the mainproduct='Y'. So the result should be like this
I can do the following
SELECT bag_no, sum(price) AS total_price
FROM myTable
GROUP BY bag_no
But this will not allow me to add product_id in the table which I also want. How can we do that?
Upvotes: 0
Views: 34
Reputation: 521684
One canonical way to do this involves joining to a subquery which finds the sums:
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';
With MySQL 8+, which supports analytic functions, we can slightly simplify the above query:
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';
Upvotes: 2