Using distinct on a column and doing order by on another column gives an error

前端 未结 11 2184
渐次进展
渐次进展 2021-02-05 14:43

I have a table: abc_test with columns n_num, k_str.

This query doesnt work:

    select distinct(n_num) from abc_test order by(k_str)

B

11条回答
  •  孤独总比滥情好
    2021-02-05 15:25

    This approach is available in SQL server 2000, you can select distinct values from a table and order by different column which is not included in Distinct. But in SQL 2012 this will through you an error "ORDER BY items must appear in the select list if SELECT DISTINCT is specified."

    So, still if you want to use the same feature as of SQL 2000 you can use the column number for ordering(its not recommended in best practice).

    select distinct(n_num) from abc_test order by 1
    

    This will order the first column after fetching the result. If you want the ordering should be done based on different column other than distinct then you have to add that column also in select statement and use column number to order by.

    select distinct(n_num), k_str from abc_test order by 2
    

提交回复
热议问题