【问题标题】:MySQL Query To For Value that Occurs more than once for the same clientIdMySQL 查询对于同一 clientId 多次出现的值
【发布时间】:2015-09-10 07:13:10
【问题描述】:

我有一个具有以下架构的 MySQL 表:

表 - charges

+=============+==============+
|  chargeName |  clientId    |
+=============+==============+
|  late fee   |    123456    |
+-------------+--------------+
|  late fee   |    123456    |
+-------------+--------------+
|   payment   |    123456    |
+-------------+--------------+
|   refund    |    782151    |
+-------------+--------------+
|  late fee   |    782151    |
+-------------+--------------+

我需要返回chargeName“滞纳金”针对同一clientId 出现多次的实例。

例如,鉴于上述情况,我希望我的查询返回“123456”,因为 clientId 有 2 笔“滞纳金”与之相关。

我尝试从SQL Query To Obtain Value that Occurs more than once 改编this answer

SELECT clientId  
FROM 
    (SELECT chargeName, count(*) as Counter, clientId  
     FROM charges
     GROUP BY `chargeName`) 
AS tbl 
WHERE Counter > 1
AND chargeName='late fee'
limit 1000;

但是,此查询仅返回一行(来自我更大的数据集),并且返回的 clientId 仅关联了 1 笔滞纳金,因此很明显它不起作用。

我怎样才能返回chargeName“滞纳金”针对同一个clientId 出现多次的实例。

【问题讨论】:

  • 这是havingcount>1的群组

标签: mysql sql database


【解决方案1】:

您可以通过 GROUP BY 和 HAVING 来完成。

SELECT clientID, chargeName
FROM charges
WHERE chargeName LIKE 'late fee'
GROUP BY clientID HAVING count(clientID) > 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多