按优先级问题获取唯一文档的记录

时间:2011-07-15 01:29:33

标签: sql oracle

我有两张桌子:

联系人:

id, name
1   Alex
2   John

文件:

id, contactID, type
1     1         1
2     1         2
...
30    1         3
31    2         1
32    2         3

我想获取联系人姓名和文档类型。 每个联系人的唯一记录。联系人可能有多种文档类型(每种类型的唯一文档),并且我对文档类型具有以下优先级:2,3,1。 例如,Alex拥有所有类型的文档,但我应该只获得:

Alex, 2

John的文档类型= 1,3,因此我应该得到:

John, 3

Oracle数据库。但是,如果你能够提供sql标准解决方案,那就太棒了

2 个答案:

答案 0 :(得分:3)

Oracle 9i +,使用:

WITH example AS (
  SELECT c.name,
         d.type,
         ROW_NUMBER() OVER (PARTITION BY c.id
                                ORDER BY CASE d.type
                                           WHEN 2 THEN 1
                                           WHEN 3 THEN 2
                                           WHEN 1 THEN 3
                                           ELSE 4
                                         END) AS rnk    
    FROM CONTACTS c
    JOIN DOCUMENTS d ON d.contactid = c.id)
SELECT e.name, e.type
  FROM example e
 WHERE e.rnk = 1

...或非子查询因子(AKA CTE)版本(仍为9i +):

SELECT e.name, e.type
  FROM (SELECT c.name,
               d.type,
               ROW_NUMBER() OVER (PARTITION BY c.id
                                      ORDER BY CASE d.type
                                                 WHEN 2 THEN 1
                                                 WHEN 3 THEN 2
                                                 WHEN 1 THEN 3
                                                 ELSE 4
                                               END) AS rnk    
          FROM CONTACTS c
          JOIN DOCUMENTS d ON d.contactid = c.id) e
 WHERE e.rnk = 1

答案 1 :(得分:2)

使用内联视图将类型映射到优先级,然后按联系人分组,然后将优先级映射回类型。

SELECT C.name
       DECODE( V.priority, 'A', 2, 'B', 3, 'C', 1 ) AS type
FROM   contacts C
    ,  (    SELECT   D.contactid
                ,    MIN( DECODE( D.type, 2, 'A', 3, 'B', 1, 'C' ) ) AS priority
            FROM     documents D
            GROUP BY D.contact_id
       ) V
WHERE  V.contactid = C.id