zoukankan      html  css  js  c++  java
  • unless it is in a subquery contained in a HAVING clause or a select list.

    sql查询报错:

    An aggregate may not appear in the WHERE clause unless it is in a
    subquery contained in a HAVING clause or a select list.

    group 语句where子句使用Max函数或SUM等函数时会提示报错,需要将引where子句换成having

    如:

    SELECT 
      SUM(M1.InvoiceTotal)-SUM(M1.AmountApplied) as PastDueAmount
      , M1.BillingID
      , M2.Name
      , M2.DelinquentDaysThreshold
      , M2.DelinquentAmountThreshold
      , DATEDIFF(d, MIN(BillingDate),GETDATE()) as DaysLate
    FROM Invoices M1 
    LEFT JOIN ClientAccounts M2 ON M1.BillingID = M2.ID
    WHERE 
      InvoiceTotal <> AmountApplied
      AND M2.DelinquentDaysThreshold > DATEDIFF(d, MIN(BillingDate),GETDATE())
      OR (SUM(M1.InvoiceTotal)-SUM(M1.AmountApplied)) > M2.DelinquentAmountThreshold
    GROUP BY 
      M1.BillingID
      , M2.Name
      , M2.DelinquentDaysThreshold
      , M2.DelinquentAmountThreshold

    会提示最上面的错误,调整成如下可通过:

    SELECT
        SUM(M1.InvoiceTotal)-SUM(M1.AmountApplied) as PastDueAmount, 
        M1.BillingID, M2.Name, 
        M2.DelinquentDaysThreshold, M2.DelinquentAmountThreshold,
        DATEDIFF(d, MIN(BillingDate),GETDATE()) as DaysLate
    FROM
        Invoices M1
        LEFT JOIN
        ClientAccounts M2 ON M1.BillingID = M2.ID
    WHERE
        InvoiceTotal <> AmountApplied
        AND
        M2.DelinquentDaysThreshold > DATEDIFF(d, MIN(BillingDate),GETDATE())
    GROUP BY
        M1.BillingID, M2.Name, 
        M2.DelinquentDaysThreshold, M2.DelinquentAmountThreshold,
        DATEDIFF(d, MIN(BillingDate),GETDATE())
    HAVING
        (SUM(M1.InvoiceTotal)-SUM(M1.AmountApplied)) > M2.DelinquentAmountThreshold

    参考:SQL查询汇总可能不会显示在WHERE子句中 https://codeday.me/bug/20181101/353176.html

  • 相关阅读:
    一个苏州IT人的5年挨踢经历经历篇(之二)
    【Java】Collection 集合框架概述
    【Java】Collection子接口:其二 Set 组接口
    【Java】【常用类】Calendar 日历类
    【郝斌C ST】01
    【Java】【常用类】Date 日期类
    【Java】Enumeration Class 枚举类
    【Java】Properties 配置信息类
    【Java】Generic 泛型
    【Java】Annotation 注解
  • 原文地址:https://www.cnblogs.com/shy1766IT/p/11172744.html
Copyright © 2011-2022 走看看