I'm having a database with with multiple records where I want to group at. For example:
cat_id | p_id | amount | sold | date | title
---------------------------------------------
1 | 1 | 4 | 3 | 2015-04-21 | title of product 1
1 | 1 | 0 | 5 | 2015-04-03 |
2 | 1 | 3 | 1 | 2015-04-21 | title of product 2
2 | 1 | 0 | 3 | 2015-04-05 |
In this table, there are two unique products, p_id 1
in cat_id 1
and p_id 1
in cat_id 2
. Now I want to get all a list of all product, sum its amount
and sold
. The title is only filled in where the amount is > 0.
So I wrote this query:
SELECT SUM (amount), SUM(sold) cat_id, p_id, title
FROM table
GROUP BY cat_id, p_id
This returns me:
cat_id | p_id | amount | sold | title
---------------------------------------------
1 | 1 | 4 | 8 |
2 | 1 | 3 | 4 |
So now I'm missing my title.
I tried something link GROUP_CONCAT(DISTINCT title)
, but that concatenates, and that's not what I'm actually looking for. I just need the title.
How would I fix this.
NOTE: Updated question