How do I select a row based on a priority value in another row?

ε祈祈猫儿з 提交于 2019-12-08 13:22:33

问题


I am using Oracle 11G and I have a table with the following columns and values and I want to select the value for each column based on the priority column. I only want one row for each ID.

ID    NAME   NAME_PRIORITY   COLOR   COLOR_PRIORITY
1     SAM       2             RED          1
1     SAM       2             GREEN        2
1     JOHN      1             BLUE         3
2     MARY      2             ORANGE       1
3     JON       2             RED          2
3     PETE      3             GREEN        1

Desired Results

ID   NAME    NAME_PRIORITY   COLOR     COLOR_PRIORITY
1    JOHN       1             RED           1
2    MARY       2             ORANGE        1
3    JON        2             GREEN         1

How do I select the NAME and COLOR with the lowest PRIORITY # and only have one row for each ID.


回答1:


one option is:

select d.id, min(name) keep (dense_rank first order by name_priority) name,
       min(name_priority) name_priority,
       min(color) keep (dense_rank first order by color_priority) color,
       min(color_priority) color_priority
  from yourtab d
 group by id;



回答2:


You can use row_number() on both the name_priority and color_priority to get the result:

select n.id,
  name, 
  name_priority,
  color,
  color_priority
from
(
  select id,
    name, 
    name_priority,
    row_number() over(partition by id order by name_priority) name_row
  from yourtable
) n
inner join
(
  select id,
    color, 
    color_priority,
    row_number() over(partition by id order by color_priority) color_row
  from yourtable
) c
  on n.id = c.id
  and n.name_row = c.color_row
where n.name_row = 1
  and c.color_row = 1

See SQL Fiddle with Demo.

Once you have the row_number() for each priority, then you will join the results on the id and the row number and only return the rows where the row number is equal to 1.




回答3:


This query uses Common Table Expression and ROW_NUMBER()

WITH nameList
AS
(
    SELECT  ID, Name,
            ROW_NUMBER() OVER (PARTITION BY ID 
                            ORDER BY NAME_PRIORITY) rn
    FROM    TableName
),
colorList
AS
(
    SELECT  a.ID, a.Name,
            b.Color, b.COLOR_PRIORITY,
            ROW_NUMBER() OVER (PARTITION BY a.ID 
                            ORDER BY COLOR_PRIORITY) rnB
    FROM    nameList a
            INNER JOIN tableName b
                ON a.ID = b.ID AND a.rn = 1
)
SELECT  ID, Name, Color, COLOR_PRIORITY
FROM    colorList
WHERE   rnB = 1
  • SQLFiddle Demo


来源:https://stackoverflow.com/questions/15252347/how-do-i-select-a-row-based-on-a-priority-value-in-another-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!