I know that the query below causes the error - ORDER BY items must appear in the select list if SELECT DISTINCT is specified.
SELECT DISTINCT city
FROM HR.Em
A query with SELECT DISTINCT
can be rewritten using GROUP BY
. So the query:
SELECT DISTINCT city
FROM HR.Employees
WHERE country = N'USA' AND region = N'WA' ;
is equivalent to:
SELECT city
FROM HR.Employees
WHERE country = N'USA' AND region = N'WA'
GROUP BY city ;
and you can't use ORDER BY birthdate
here either. The reason is the same for both queries. There may be many (more than one) rows with same city
but different birthdate
. Which one should be used for the ordering (if it was allowed?)
You can however use aggregate functions with a GROUP BY
query:
SELECT city
FROM HR.Employees
WHERE country = N'USA' AND region = N'WA'
GROUP BY city
ORDER BY MIN(birthdate) ; -- or MAX(birthdate)
try this:
select city
from (
SELECT city, min(birthdate) as birthdate
FROM HR.Employees
WHERE country = N'USA' AND region = N'WA'
group by city
) as t
order by birthdate