【问题标题】:Why this COUNT in HAVING not working expectedly?为什么这个 COUNT in HAVING 没有按预期工作?
【发布时间】:2019-06-04 07:47:21
【问题描述】:

我正在使用以下查询来选择所有出现超过 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`

我哪里做错了?

【问题讨论】:

  • 您的期望只是bp_customer_idbp_customer_id 以及status_id, COUNT(`status_id`) ?
  • @Arulkumar、bp_customer_id 以及 status_idCOUNT... 全部
  • ​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 `status_id`) >= 3) GROUP BY `status_id`, `bp_customer_id` ORDER BY `bp_customer_id`​
  • @PetSerAl 太好了!这就是我一直在寻找的。谢谢。
  • @user5307298 我已根据您的评论更新了my answer

标签: mysql


【解决方案1】:

尚未检查这是否可行,但进行子选择可能会有所帮助

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`  

【讨论】:

  • 但是为什么您的查询选择具有bp_customer_id 232、999 的行...对于特定的status_id 仅出现一次。这是不正确的。
【解决方案2】:

如果您在输出结果中只需要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`

【讨论】:

  • 您的解决方案的第二个版本几乎是正确的,只是您仍然获取了那些只有一种状态 ID 的客户。例如,客户 232 和 999 等只有一个状态 ID。 PetSerAl 完全符合我的要求。
  • ​COUNT(DISTINCT `bp_customer_id`)​ 不能超过 1 和 ​GROUP BY `bp_customer_id`​
  • @Arulkumar 还不正确。其实你应该做HAVING COUNT(DISTINCT `status_id`) >= 3 )
猜你喜欢
  • 1970-01-01
  • 2022-10-14
  • 2020-07-24
  • 2011-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-04
相关资源
最近更新 更多