Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

group-by

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 through every solution I've seen but they're with more involved queries so it was very hard for me to pick out the problem. I made a little dummy table to illustrate my problem.

table name: grouptest

id  name
1   Mel
2   Lucy
3   Mandy
4   Mel
5   Mandy
6   Mel

I want to find out how many times each name shows up, to produce a table like:

3 Mel
2 Mandy
1 Lucy

Here's the query I think should work:

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

And I get the error:

Each GROUP BY expression must contain at least one column that is not an outer reference.

Help!

like image 419
Mel Avatar asked Jul 31 '12 18:07

Mel


People also ask

Can we use multiple columns in GROUP BY?

Usage of Group By Multiple ColumnsWe can use the group by multiple-column technique to group multiple records into a single record. All the records with the same values for the respective columns mentioned in the grouping criteria can be grouped as a single column using the group by multiple-column technique.

Should GROUP BY have all the columns in the SELECT?

If you specify the GROUP BY clause, columns referenced must be all the columns in the SELECT clause that do not contain an aggregate function. These columns can either be the column, an expression, or the ordinal number in the column list.

Can we use GROUP BY and count together in SQL?

The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.

How do I Group A column in SQL?

The GROUP BY Statement in SQL is used to arrange identical data into groups with the help of some functions. i.e if a particular column has same values in different rows then it will arrange these rows in a group. Important Points: GROUP BY clause is used with the SELECT statement.


2 Answers

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))
like image 116
Taryn Avatar answered Nov 15 '22 00:11

Taryn


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))
like image 27
Lamak Avatar answered Nov 14 '22 23:11

Lamak