I’m trying to make a list of the best items in the database. An item is better if the profit is higher. The problem is an item a can have duplicates like 500 profit at 10 o’clock and 750 profit at 14 o’clock.
My current code would show both attempts and php I filter this. This way I get the item A once, but I can’t tell the total profit of item A.
My SQL statement is this: SELECT item FROM category WHERE endtime >=? ORDER BY profit DESC LIMIT 15
endtime is a unixtime stamp so it shows items from the last week.
And with php, I filter using array_unique($items, SORT_REGULAR);
I would like SQL to give a list of 5 most profitable items with profit and item where duplicates get to add up.
So this: a 500, b 250, c 350, b 100, a 25, c 50
becomes: a 525, c 400, b 350
2
Answers
If i understood correctly you have a table given like this:
and you want:
This can be achieved quite easily using
GROUP BY
andSUM
This query should give you the result you want (without sample data it’s hard to be certain). Basically you need to use
SUM
to sum the profit andGROUP BY item
to get sums for each different item.