我有一个简单的查询
select id,
(select sum(totalin) from xorderextra where xorderextra.id = xoi.id) as totalin,
from xorderinfo xoi
group by xoi.id
having (select sum(totalin) from xorderextra where xorderextra.id = xoi.id) > 1000
现在我想知道是否有更好的方法来替换带语句的sum过滤器。这是设置事物的正确方法吗,这会伤害查询,即。是否必须将数字相加两次?
* 新案例*
select xoi.id,
sum(xex.totalin) as totalin,
sum(xooc.totalout) as totalout,
from xorderinfo xoi
inner join xorderextra xex on xex.id = xoi.id
inner join xorderout xoo on xoo.rid = xoi.id
inner join xorderoutcalc xooc on xooc.obracunid = xoo.obracunid
group by xoi.id
having sum(xex.totalin) > 1000
这会返回错误的结果,我该如何解决?
答案 0 :(得分:1)
您可以加入并大大提高效果!
select id,
sum(xex.totalin) as totalin,
from xorderinfo xoi
inner join xorderextra xex on xorderextra.id = xoi.id
group by xoi.id
having sum(xex.xorderextra) > 1000
答案 1 :(得分:1)
您可以使用cte和SUM OVER
重写它:
WITH cte AS(
SELECT id
, SUM(xoi.totalin) OVER (PARTITION BY xoi.id) As TotalIn
FROM xorderinfo xoi
)
SELECT cte.* FROM cte
WHERE TotalIn > 1000