【发布时间】:2012-08-23 12:37:15
【问题描述】:
在按product_id 分组之前,如何按'n', 'p', 'd', 'c', 'b', 'x' 的顺序按ap_status 对所有行进行排序?
当您删除 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
所以我在查看了一些类似的问题后尝试使用HAVING,但这在小组之前也不起作用
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`)
非常感谢任何建议
【问题讨论】:
-
也许您可以将您的 ORDER BY 查询用作另一个查询的子查询,该查询在其结果上使用 GROUP BY。或使用临时表或某事。
-
向我们展示您的查询。无论如何,如果您要分组并应用聚合函数,则不需要顺序
标签: mysql group-by sql-order-by