Using DISTINCT for specific columns

前端 未结 3 1528
小鲜肉
小鲜肉 2021-01-24 15:36
select distinct  employee_id, first_name,  commission_pct, department_id from
employees;

When I use the above query it results in distinct combination

相关标签:
3条回答
  • 2021-01-24 15:44

    Can you try this one?

    SELECT
      NAME1,
      PH
    FROM
          (WITH T
               AS (SELECT
                        'mark' NAME1,
                        '1234567' PH
                  FROM
                        DUAL
                  UNION ALL
                  SELECT
                        'bailey',
                        '456789'
                  FROM
                        DUAL
                  UNION ALL
                  SELECT
                        'mark',
                        '987654'
                  FROM
                        DUAL)
           SELECT
                NAME1,
                PH,
                ROW_NUMBER ( ) OVER (PARTITION BY NAME1 ORDER BY NAME1) SEQ
           FROM
                T)
    WHERE
          SEQ = 1;
    

    If you dont care on a specific row, then use aggregate functions

    SELECT
          NAME1,
          MAX ( PH ) PH
    FROM
          T
    GROUP BY
          NAME1;
    
    0 讨论(0)
  • 2021-01-24 16:08

    What you request is impossible. You cannot select all the employee ids but have only distinct commission_pct and department_id.

    So think it over, what you want to show:

    • All distinct commission_pct, department_id only?
    • All distinct commission_pct, department_id and the number of relevant employees?
    • All distinct commission_pct, department_id and the relevant employees comma separated?
    • All employees, but with nulls when commission_pct and department_id are the same as in the line before?

    The first can be solved with DISTINCT. The second and third with GROUP BY (plus count or listagg). The last would be solved with the analytic function LAG.

    0 讨论(0)
  • 2021-01-24 16:08

    You have to remove two columns before distinct

    select distinct commission_pct, department_id from
    employees; 
    

    Indeed, if your second query would work, what do you expect to see in the first two columns? Consider example data

    | employee_id | first_name | commission_pct | department_id |
    |     1       |     "x"    |      "b"       |       3       |
    |     2       |     "y"    |      "b"       |       3       |
    |     1       |     "x"    |      "c"       |       4       |
    |     2       |     "y"    |      "c"       |       4       |
    

    You expect to get only two row result like this

    | employee_id | first_name | commission_pct | department_id |
    |     ?       |      ?     |      "b"       |       3       |
    |     ?       |      ?     |      "c"       |       4       |
    

    But what do you expect in the first two column?

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