JPickup
JPickup

Reputation: 388

ORDER BY specified order before GROUP BY

How would i order all rows by ap_status in this order 'n', 'p', 'd', 'c', 'b', 'x' before grouping by product_id?

This query orders correctly when you remove the GROUP BY

SELECT `account_id`, `product_id`, `product_name`, `ap_status`, count(`ap_id`) as `num` 
FROM (accounts_products_view)
WHERE `account_id` = 13
/*GROUP BY `product_id`*/
ORDER BY FIELD(`ap_status`, 'n', 'p', 'd', 'c', 'b', 'x') desc

So i tried using HAVING after viewing some similar questions but, this is not working before the group by either

SELECT account_id, product_id, product_name, ap_status, count(ap_id) as num,
CASE
WHEN ap_status = 'n' then 1
WHEN ap_status = 'p' then 2
WHEN ap_status = 'd' then 3
WHEN ap_status = 'c' then 4
WHEN ap_status = 'b' then 5
WHEN ap_status = 'x' then 6
END as `order`

FROM (accounts_products_view)
WHERE `account_id` = 13
GROUP BY product_id
HAVING `order` = MIN(`order`)

Any suggestions are greatly appreciated

Upvotes: 1

Views: 385

Answers (1)

mkk
mkk

Reputation: 7693

you might want to try:

SELECT *, count(`ap_id`) as `num` FROM (
        SELECT `account_id`, `product_id`, `product_name`, `ap_status`, `ap_id`
        FROM (accounts_products_view)
        WHERE `account_id` = 13
        /*GROUP BY `product_id`*/
        ORDER BY FIELD(`ap_status`, 'n', 'p', 'd', 'c', 'b', 'x') desc
    ) as res GROUP BY product_id

but keep in mind it is INCORRECT!. If you use group by, then either you need to use aggregate function, like SUM() for example or specify the field in group by as well. In your example the fields that you might correctly retreive are product_id and nothing else. Because of MySQL bug or something you don't get exception on this query, but in postgresql you will get exception. If you have 2 rows with the same product_id and different ap_status, in theory you are not able to say which one should be returned by the query. I guess you have figured out that in MySQL the first row will be returned, that is why you want to order the rows before executing group by. Keep in mind that this is incorrect and very hackish.

Upvotes: 1

Related Questions