如何根据另一行中的优先级值选择行?

时间:2013-03-06 16:09:58

标签: sql oracle oracle11g

我使用的是Oracle 11G,我有一个包含以下列和值的表,我想根据优先级列选择每列的值。我只希望每个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

期望的结果

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

如何选择PRIORITY#最低的NAME和COLOR,每个ID只有一行。

3 个答案:

答案 0 :(得分:2)

一个选项是:

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;

答案 1 :(得分:0)

您可以在name_prioritycolor_priority上使用row_number()来获得结果:

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

请参阅SQL Fiddle with Demo

每个优先级都有row_number()后,您将在id和行号上加入结果,只返回行号等于1的行。

答案 2 :(得分:0)

此查询使用Common Table ExpressionROW_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
相关问题