【问题标题】:SQL COUNT function for results "greater than or equal to"结果“大于或等于”的 SQL COUNT 函数
【发布时间】:2015-11-07 04:21:25
【问题描述】:

我目前有一个查询,它返回每个客户持有的帐户总数,但我如何使它只返回拥有超过 1 个帐户的客户?

SELECT C.customerID, COUNT(O.accNumber) AS "total"
FROM Customer C, Owns O
WHERE C.customerID = O.customerID
GROUP BY C.customerID

【问题讨论】:

    标签: sql count


    【解决方案1】:

    您的问题的答案是HAVING。但是,您需要学习使用正确的JOIN 语法。简单规则:永远不要FROM 子句中使用逗号。 总是使用明确的JOIN 语法。

    SELECT C.customerID, COUNT(O.accNumber) AS total
    FROM Customer C JOIN
         Owns O
         ON C.customerID = O.customerID
    GROUP BY C.customerID
    HAVING COUNT(*) > 1;
    

    其实你甚至不需要JOIN

    SELECT o.customerID, COUNT(o.accNumber) AS total
    FROM Owns o
    GROUP BY o.customerID
    HAVING COUNT(*) > 1;
    

    这要简单得多。

    【讨论】:

    • 第二个无连接版本只有在我们假设所有“Owns”记录在“Customer”中有父记录时才是正确的。这看起来很直观,但可能不是真的。
    • @JosephStyons 。 . .他们都加入了CustomerId,所以看起来关系很好。
    • 如果我在这里猜的话,“HAVING COUNT(*) > 1”语句会查看整数大于 1 的行?
    • COUNT(*) > 1 表示每个组有不止一行。由于*,它没有查看任何特定列。
    【解决方案2】:

    添加 HAVING 子句

    SELECT C.customerID, COUNT(O.accNumber) AS "total"
    FROM Customer C, Owns O
    WHERE C.customerID = O.customerID
    GROUP BY C.customerID
    HAVING COUNT(*) > 1
    

    【讨论】:

      【解决方案3】:

      请尝试

      WHERE C.customerID = O.customerID AND count(O.accNumber) > 1 
      

      【讨论】:

        猜你喜欢
        • 2018-08-05
        • 2015-05-22
        • 1970-01-01
        • 2023-03-19
        • 1970-01-01
        • 1970-01-01
        • 2012-07-09
        • 2014-11-09
        • 2011-01-25
        相关资源
        最近更新 更多