Tuesday, October 28, 2008

SQL: DISTINCT and SUM using one SELECT Statement

When you do this, you'll have an error like this:

Msg 8120, Level 16, State 1, Line 1
Column 'table1.column1' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

so simply put columns in the GROUP BY clause and it will work fine:

SELECT distinct(column1), column2, SUM(column3)/3 FROM table1 WHERE column2 = something GROUP BY column1, column2

No comments: