There are a multitude of questions relating to the "Each GROUP BY
expression must contain at least one column that is not an outer reference." error, and the inclusion of a constant value in the GROUP BY
clause is often the cause of the error.
I'm actually converting some SQL from a database that allows constants in the GROUP BY
clause, so I'm wondering two things:
Why does MS SQL Server not allow constants in the
GROUP BY
clause?Why does putting a constant in the
GROUP BY
clause produce this error and not a "Don't put constants in yourGROUP BY
clause, idiot." error?
Here's a quick example of the error occurring. The following code bombs out on the third SELECT
statement, with the incongruous error message.
DECLARE @demo TABLE
( groupCol1 int
, groupCol2 int);
INSERT INTO @demo VALUES(1,1);
INSERT INTO @demo VALUES(1,1);
INSERT INTO @demo VALUES(2,1);
INSERT INTO @demo VALUES(1,2);
INSERT INTO @demo VALUES(1,2);
INSERT INTO @demo VALUES(2,2);
INSERT INTO @demo VALUES(3,1);
INSERT INTO @demo VALUES(3,1);
INSERT INTO @demo VALUES(1,3);
INSERT INTO @demo VALUES(1,3);
SELECT * FROM @demo;
SELECT * FROM @demo GROUP BY groupCol1, groupCol2;
SELECT *, 'x' FROM @demo GROUP BY groupCol1, groupCol2, 'x';
GROUP BY
expression must contain a non-outer column reference. In your third query, you have threeGROUP BY
expressions and the third contains absolutely no column references at all. – CleveiteGROUP BY
must contain at least one non-outer reference. It does. I'm asking why it reports that error when that error apparently does not apply. – BergsteinGROUP BY
expression in your third query is'x'
. That contains no column references. It's not referring to the entireGROUP BY
clause but to each expression contained therein. – Cleveite