Question

I have a t-sql query where sum function is duplicated. How to avoid duplicating those statements?

select 
    Id,
    sum(Value)
from
    SomeTable
group by 
    Id
having
    sum(Value) > 1000
Was it helpful?

Solution

It look like table aliasing is not supported. I think with should work:

with tmptable (id,sumv)
as
(select
    Id,
    sum(Value) as sumv
from
    SomeTable
group by 
    Id  
)
select
    id,
    sumv 
from
    tmptable
where
   sumv>1000

And a fiddle:

http://sqlfiddle.com/#!6/0d3f2/2

OTHER TIPS

You need to remove the sum(Value) from the group by clause.

You can use GROUP BY 1, 2 to group by (in this case) the first and second columns, and thus avoid duplication in the GROUP BY clause.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top