Why can't I perform an aggregate function on an expression containing an aggregate but I can do so by creating a new select statement around it?

后端 未结 7 629
囚心锁ツ
囚心锁ツ 2020-12-09 02:48

Why is it that in SQL Server I can\'t do this:

select  sum(count(id)) as \'count\'
from    table

But I can do

select sum(x.         


        
7条回答
  •  醉梦人生
    2020-12-09 03:29

    Microsoft SQL Server doesn’t support it.

    You can get around this problem by using a Derived table:

    select sum(x.count)
    from
    (
        select  count(id) as 'count'
        from    table   
    ) x
    

    On the other hand using the below code will give you an error message.

    select  sum(count(id)) as 'count'
    from    table
    

    Cannot perform an aggregate function on an expression containing an aggregate or a subquery

提交回复
热议问题