如何对具有聚合函数的 Oracle 查询进行分组
Posted
技术标签:
【中文标题】如何对具有聚合函数的 Oracle 查询进行分组【英文标题】:how to group oracle queries which has aggregate functions 【发布时间】: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;
【问题讨论】:
【参考方案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,你是完全正确的。复制和粘贴时出现拼写错误;)谢谢以上是关于如何对具有聚合函数的 Oracle 查询进行分组的主要内容,如果未能解决你的问题,请参考以下文章