我正在使用以下查询来选择所有出现了3次以上且状态ID为的客户。该查询还计算为客户显示状态ID的次数:
SELECT `bp_customer_id`, `status_id`, COUNT(`status_id`) FROM `bp_orders`
GROUP BY `status_id`, `bp_customer_id`
ORDER BY `bp_customer_id`
它提供以下输出:
在上表中,客户1000出现3次。因此,我只选择那些在表中出现3次或3次以上的客户。我们该怎么做?我在上面的查询中使用了COUNT()
和HAVING
,但是没有运气。
SELECT `bp_customer_id`, `status_id`, COUNT(`status_id`) FROM `bp_orders`
GROUP BY `status_id`, `bp_customer_id`
HAVING COUNT(`bp_customer_id`) >= 3
ORDER BY `bp_customer_id`
我在哪里做错了?
答案 0 :(得分:0)
如果仅在输出结果中需要bp_customer_id
,请忽略SELECT
语句中的其他列
SELECT `bp_customer_id`
FROM `bp_orders`
GROUP BY `bp_customer_id`
HAVING COUNT(DISTINCT `bp_customer_id`) >= 3
ORDER BY `bp_customer_id`
根据您的评论,您需要bp_customer_id
以及status_id和COUNT。因此,使用以上查询作为子查询并基于bp_customer_id
,您也可以获取其他详细信息。因此,有效的查询是:
SELECT `bp_customer_id`,
`status_id`,
COUNT(`status_id`)
FROM `bp_orders`
WHERE `bp_customer_id` IN (
SELECT `bp_customer_id`
FROM `bp_orders`
GROUP BY `bp_customer_id`
HAVING COUNT(DISTINCT `bp_customer_id`) >= 3
)
GROUP BY `bp_customer_id`, `status_id`
ORDER BY `bp_customer_id`
答案 1 :(得分:0)
没有检查这是否可行,但是进行子选择可能会有帮助
SELECT A.`bp_customer_id`, A.`status_id`, COUNT(`status_id`) FROM `bp_orders` A, {
SELECT COUNT(*) AS customerCount, `bp_customer_id` FROM `bp_orders` GROUP BY `bp_customer_id`
} B WHERE A.`bp_customer_id` = B.`bp_customer_id`
AND B.customerCount >= 3
GROUP BY A.`status_id`, A.`bp_customer_id`
ORDER BY A.`bp_customer_id`