I have table A with five rows and the following values:
Column1 Column2 Column3 Column4
------- ------- ------- -------
anna ben cat d
anna ben cat e
anna ben cat f
gina hugh ken m
gina hugh ken p
I want to add another column called Column5. The value of Column 5 will be 3 for the first 3 rows and 2 on the next 2 rows:
Column1 Column2 Column3 Column4 Column5
------- ------- ------- ------- -------
anna ben cat d 3
anna ben cat e 3
anna ben cat f 3
gina hugh ken m 2
gina hugh ken p 2
How I did this:
SELECT DISTINCT COUNT (DISTINCT t1.Column4) AS Column5,
Column1, Column2, Column3, Column4
FROM TableA AS t1
GROUP BY Column1, Column2, Column3;
This doesn’t work:
Msg 8120, Level 16, State 1, Procedure COUNT, Line 29
Column ‘Column4’ invalid in the select list because it is not contained in either an
aggregate function or the GROUP BY clause.
Any help please? Much appreciated.
PS: If I add Column4 in the group by clause, I get only values of “1” in the result table in Column5.
One other way to do what you want would be to select distinct rows first, then apply the windowed COUNT() function: