【问题标题】:How to avoid duplicating statements with grouping functions?如何避免使用分组函数重复语句?
【发布时间】:2014-03-24 21:24:56
【问题描述】:

我有一个重复 sum 函数的 t-sql 查询。 如何避免重复这些语句?

select 
    Id,
    sum(Value)
from
    SomeTable
group by 
    Id
having
    sum(Value) > 1000

【问题讨论】:

  • sum(value) 的分组看起来不太好......

标签: sql group-by having-clause


【解决方案1】:

似乎不支持表别名。 我认为with 应该可以工作:

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

还有一个小提琴:

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

【讨论】:

    【解决方案2】:

    您需要从 group by 子句中删除 sum(Value)。

    【讨论】:

      【解决方案3】:

      您可以使用GROUP BY 1, 2 按(在这种情况下)第一列和第二列进行分组,从而避免GROUP BY 子句中的重复。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-09
        • 1970-01-01
        • 1970-01-01
        • 2016-06-12
        • 2020-09-19
        • 2012-09-17
        • 2013-04-19
        • 2020-02-14
        相关资源
        最近更新 更多