1

グループ化する前に、すべての行ap_statusをこの順序で並べ替えるにはどうすればよいですか?'n', 'p', 'd', 'c', 'b', 'x'product_id

このクエリは、を削除すると正しく順序付けられます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`)

任意の提案は大歓迎です

4

1 に答える 1

1

あなたが試してみたいかもしれません:

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

しかし、それは間違っていることに注意してください。group by を使用する場合は、SUM() などの集計関数を使用するか、group by でフィールドを指定する必要があります。あなたの例では、正しく取得できるフィールドは product_id であり、他には何もありません。MySQL のバグか何かのため、このクエリでは例外が発生しませんが、postgresql では例外が発生します。product_id が同じで ap_status が異なる 2 つの行がある場合、理論的には、クエリでどちらを返す必要があるかを判断できません。MySQL では最初の行が返されることがわかっていると思います。そのため、group by を実行する前に行を並べ替える必要があります。これは正しくなく、非常にハックであることを覚えておいてください。

于 2012-08-23T12:50:00.640 に答える