SQL error when using Group By: Each GROUP BY expression must contain at least one column that is not an outer reference

前端 未结 3 1186
小鲜肉
小鲜肉 2021-01-18 16:23

I\'ve been getting this error when doing what I thought to be one of the simplest possible queries! I see other people have run into issues here too, and I\'ve looked throug

相关标签:
3条回答
  • 2021-01-18 16:49

    Lose the ' on the GROUP BY:

    SELECT Count(id), Name 
    FROM groupbytest 
    GROUP BY Name
    

    If name is a text, then you need to cast it to VARCHAR, but you might be truncating your column.

    SELECT Count(id), CAST(Name AS VARCHAR(8000)) AS Name
    FROM groupbytest 
    GROUP BY CAST(Name AS VARCHAR(8000))
    
    0 讨论(0)
  • 2021-01-18 17:02

    You want:

    SELECT Count(id), [Name]
    FROM groupbytest 
    GROUP BY [Name]
    

    GROUP BY 'Name' tries to group on the literal string 'Name', not the column Name.

    Name also may be a reserved word, hence the brackets around it, although you're better off not calling the column Name.

    0 讨论(0)
  • 2021-01-18 17:05

    You have quotes around the Name field which are unneeded.

    SELECT Count(id), Name
    FROM grouptest
    GROUP BY Name
    

    Based on your comments, you need to CAST your Name column:

    SELECT Count(id), Cast(Name as Varchar(max)) Name
    FROM grouptest
    GROUP BY Cast(Name as Varchar(max))
    
    0 讨论(0)
提交回复
热议问题