Search code examples
sqlgroup-byhaving-clause

How to avoid duplicating statements with grouping functions?


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

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