gpt4 book ai didi

oracle - Oracle 中的条件分组依据

转载 作者:行者123 更新时间:2023-12-01 00:46:07 27 4
gpt4 key购买 nike

我正在尝试编写一个查询来获取具有条件的表的总和。
例如这张 table

area    |    machine    |    status    |    qty

1 | machine1 | inprocess | 210
1 | machine2 | pending | 120
1 | machine3 | done | 50
2 | machine1 | inprocess | 30
2 | machine2 | done | 170

我想要的结果是
area  |  inprocess sum  |  pending sum   | done sum  |  all sum

1 | 210 | 120 | 50 | 380
2 | 30 | 0 | 170 | 200

我正在考虑带条件的 group by 子句,但我似乎无法获得解决此问题所需的解决方案。我试过的是
select distinct 
area,
(select sum(qty) from table
where status = 'inprocess'
and area = mainTable.area) as inprocess sum
(select sum(qty) from table
where status = 'pending'
and area = mainTable.area) as pending sum
(select sum(qty) from table
where status = 'done'
and are = mainTable.area) as done sum
from table mainTable

在某种程度上,它确实有效,但是当我尝试检查我是否获得了正确的数量时,我似乎无法将实际值与我的查询结果相匹配。 (我正在处理一个更大的数据集,数百万条记录)。我想我真正想要的是一个 group by 子句,我可以用它来放置条件,这样它只会聚合与条件匹配的记录。请教绝地大师

最佳答案

您可以尝试使用数据透视查询:

SELECT t.area, SUM(t.isum) AS "inprocess sum",
SUM(t.psum) AS "pending sum",
SUM(t.dsum) AS "done sum",
SUM(t.isum) + SUM(t.psum) + SUM(t.dsum) AS "all sum"
FROM
(
SELECT area,
CASE WHEN status = 'inprocess' THEN qty ELSE 0 END AS isum,
CASE WHEN status = 'pending' THEN qty ELSE 0 END AS psum,
CASE WHEN status = 'done' THEN qty ELSE 0 END AS dsum
FROM mainTable
) t
GROUP BY t.area

如果您使用的是 Oracle 11g 或更高版本,那么您还可以利用内置的 PIVOT功能:
SELECT area, isum_qty AS "inprocess sum", psum_qty AS "pending sum", dsum_qty AS "done sum",
isum_qty + psum_qty + dsum_qty AS "all sum"
FROM
(
SELECT area, status
FROM mainTable
)
PIVOT
(
SUM(qty) AS qty
FOR status IN ('inprocess' AS "isum", 'pending' AS "psum", 'done' AS "dsum")
)
ORDER BY area ASC;

关于oracle - Oracle 中的条件分组依据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34327519/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com