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

前端 未结 11 2159
渐次进展
渐次进展 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:35

    You might think about using group by instead:

    select n_num
    from abc_test
    group by n_num
    order by min(k_str)
    
    0 讨论(0)
  • 2021-02-05 15:37

    As far as i understood from your question .

    distinct :- means select a distinct(all selected values should be unique). order By :- simply means to order the selected rows as per your requirement .

    The problem in your first query is For example : I have a table

    ID name
    01 a
    02 b
    03 c
    04 d 
    04 a
    

    now the query select distinct(ID) from table order by (name) is confused which record it should take for ID - 04 (since two values are there,d and a in Name column). So the problem for the DB engine is here when you say order by (name).........

    0 讨论(0)
  • 2021-02-05 15:43

    did you try this?

    SELECT DISTINCT n_num as iResult
    FROM abc_test 
    ORDER BY iResult
    
    0 讨论(0)
  • 2021-02-05 15:45

    The first query is impossible. Lets explain this by example. we have this test:

    n_num k_str
    2     a
    2     c
    1     b
    

    select distinct (n_num) from abc_test is

    2
    1
    

    Select n_num from abc_test order by k_str is

    2
    1
    2
    

    What do you want to return

    select distinct (n_num) from abc_test order by k_str?

    it should return only 1 and 2, but how to order them?

    0 讨论(0)
  • 2021-02-05 15:45

    According to SQL Standards, a SELECT clause may refer either to as clauses ("aliases") in the top level SELECT clause or columns of the resultset by ordinal position, and therefore nether of your queries would be compliant.

    It seems Oracle, in common with other SQL implemetations, allows you to refer to columns that existed (logically) immediately prior to being projected away in the SELECT clause. I'm not sure whether such flexibility is such a good thing: IMO it is good practice to expose the sort order to the calling application by including the column/expressions etc in the SELECT clause.

    As ever, you need to apply dsicpline to get meaningful results. For your first query, the definition of order is potentially entirely arbitrary.You should be grateful for the error ;)

    0 讨论(0)
提交回复
热议问题