I have a table with these columns (MS SQL-Server 2008);
city cityDate
and rows like this;
- Porto | 20.11.1988
- Porto | 19.11.1988
- Lisbon | 21.11.1988
What I want is ordering the date column (desc) and getting the distinct values of city. So the resut should be;
- Lisbon
- Porto
I tried;
select distinct(city) from TableCity order by cityDate desc
but the output is;
Msg 145, Level 15, State 1, Line 1 ORDER BY items must appear in the
select list if SELECT DISTINCT is specified.
You just need to use group by instead of distinct:
Suppose T is your Table:
–TEST 1:
–Result: This still displays the three rows because City Date of Porto is not the same,but if Porto City Date is the same it will display only two rows.
–TEST 2:
OR
you can use CTE:
–Result:
Regards