0

我正在使用 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

如何选择 NAME 和 COLOR 具有最低 PRIORITY # 并且每个 ID 只有一行。

4

3 回答 3

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;
于 2013-03-06T16:23:27.883 回答
0

您可以row_number()同时使用name_priorityandcolor_priority来获得结果:

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 的行。

于 2013-03-06T16:16:07.953 回答
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
于 2013-03-06T16:16:30.350 回答