SQL Server 2005 error when grouping using subquery

前端 未结 2 1016
长情又很酷
长情又很酷 2021-01-28 13:06

Using SQL Server 2005 I\'m trying to group based on a case statement with a subquery, but I\'m getting an error (\"Each GROUP BY expression must contain at least one column refe

2条回答
  •  无人共我
    2021-01-28 13:24

    To start, if we give the full error, it should read "Each GROUP BY expression must contain at least one column that is not an outer reference."

    To understand the error, we need to clarify what is meant by an 'outer reference'

    (Note: in this case it has nothing to do with inner or outer joins)

    The inner and outer are in reference to the main query and it's subqueries. In this case the EXISTS is the subquery and it is a correlated subquery as it has an outer reference of #header.header, which is referencing the outer table #header, whereas any reference to #detail would be considered as inner references.

    So in essence, because the CASE utilises a correlated subquery that references the outer query, then this fires the error state, beacuse this error message appears when you try to use only expressions in a GROUP BY clause that are interpreted as outer references.

    Subqueries can be used in GROUP BY, but not correlated subqueries.

    Confusingly, the same error can be generated by a non-subqueried, simpler query such as

    select 
     case when header=1 then 1 
          else 0 
     end headeris1, 
     'constant' 
    from #header 
    group by case when header=1 then 1 else 0 end , 'constant'
    

    or even replacing the constant with a @variable

    Clear as mud?

    Kev

提交回复
热议问题