Reason for - ORDER BY items must appear in the select list if SELECT DISTINCT is specified

前端 未结 2 539
攒了一身酷
攒了一身酷 2021-01-05 20:28

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         


        
相关标签:
2条回答
  • 2021-01-05 21:30

    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)
    
    0 讨论(0)
  • 2021-01-05 21:30
    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
    
    0 讨论(0)
提交回复
热议问题