【问题标题】:how to group oracle queries which has aggregate functions如何对具有聚合函数的 Oracle 查询进行分组
【发布时间】:2021-12-12 22:03:03
【问题描述】:

上面写着“不是 groupby 函数”。当我将 D.unitpricef 添加到 groupby 时,它没有显示任何错误,但结果它多次显示相同的 itmcode。一项代码应该只显示一次

SELECT 
    ItemCode, 
    case when H.InvoType = 1 then concat(ItemCode,' ( SLT Equipment )' ) else concat(ItemCode,' ( 
  CONBES Eqipment )' ) end as EquName,
    case when TRIM(SUM(QTY)) is null then ''  else TRIM(TO_CHAR(SUM(QTY),'999999')) end as QTY,
     CAST( (SUM(QTY) * D.unitpricef) AS NUMBER(38,2)) AS Amount
    FROM Invoicedetails D 
    INNER JOIN  
    invoiceheader H ON D.InvoiceNo = H.InvoiceNo 
    INNER JOIN Equipment E ON E.EquCode = ItemCode
    WHERE 
    H.CancelStat= 0 
    AND H.ReceiptStat = 1  
    AND H.BCCODE = 'xxx'
    GROUP BY ItemCode,H.InvoType ORDER BY ItemCode ASC;

【问题讨论】:

    标签: oracle group-by aggregate-functions


    【解决方案1】:

    您需要使用与聚合函数关联的相同表达式来group by

    SELECT 
        ItemCode, 
        case when H.InvoType = 1 then concat(ItemCode,' ( SLT Equipment )' ) else concat(ItemCode,' ( CONBES Eqipment )' ) end as EquName,
        case when TRIM(SUM(QTY)) is null then ''  else TRIM(TO_CHAR(SUM(QTY),'999999')) end as QTY,
        CAST( (SUM(QTY) * D.unitpricef) AS NUMBER(38,2)) AS Amount
        FROM Invoicedetails D 
        INNER JOIN  
        invoiceheader H ON D.InvoiceNo = H.InvoiceNo 
        INNER JOIN Equipment E ON E.EquCode = ItemCode
        WHERE 
        H.CancelStat= 0 
        AND H.ReceiptStat = 1  
        AND H.BCCODE = 'xxx'
        GROUP BY 
        ItemCode
        case when H.InvoType = 1 then concat(ItemCode,' ( SLT Equipment )' ) else concat(ItemCode,' ( CONBES Eqipment )' ) end 
      
        ORDER BY ItemCode ASC;
    

    【讨论】:

    • 我认为 case when TRIM(SUM(QTY)) is null then '' else TRIM(TO_CHAR(SUM(QTY),'999999')) end 不应该归入 group by 子句。
    • @AnkitBajpai,你是完全正确的。复制和粘贴时出现拼写错误;)谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    • 1970-01-01
    相关资源
    最近更新 更多