在having子句中使用sum

时间:2012-05-15 12:16:28

标签: tsql sum

我有一个简单的查询

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

这会返回错误的结果,我该如何解决?

2 个答案:

答案 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