SQL - 根据优先级选择行

时间:2013-02-23 13:09:07

标签: sql oracle oracle10g oracle11g

鉴于以下两个表:

PRODUCT_CATEGORIES

PRODUCT_CATEGORY    PRIOTITY

BOOK               100
VIDEO              200
CD                 300

PRODUCT_TYPES

PRODUCT_TYPE_ID PRODUCTID   PRODUCT_CATEGORY
1               1001        VIDEO
2               1001        CD
3               1002        BOOK
4               1002        VIDEO
5               1003        BOOK

如何加入这两个表,以便从PRODUCT_TYPES中选择所有行,如果有重复的产品,我只选择优先级最高的行。

例如,对于PRODUCTID 1002,我只想要一个类别为VIDEO的行,因为VIDEO的优先级高于BOOK(表格中另一个1002产品的类别)。

这是我尝试过但我似乎只是重复。

select product_type_id, productid, product_category
from product_types pt
join product_categories pc on (pc.product_category=pt.product_category)

另一种方法是按降序排序product_category并选择rownum = 1的第一行,但我怀疑这不是最佳解决方案。

3 个答案:

答案 0 :(得分:3)

WITH recordList 
AS
(
    SELECT  a.Product_TypeID,
            a.ProductID,
            a.Product_Category,
            b.Priority,
            ROW_NUMBER() OVER (PARTITION BY a.ProductID
                                ORDER BY b.Priority) RN
    FROM    Product_Types a
            INNER JOIN Product_Categories b
                ON a.Product_Category = b.Product_Category
)
SELECT      Product_TypeID,
            ProductID,
            Product_Category,
            Priority
FROM    recordList
WHERE   RN = 1

答案 1 :(得分:3)

尝试以下查询:

 SELECT PT.*
 FROM PRODUCT_CATEGORIES PC INNER JOIN PRODUCT_TYPES PT
 ON PC.PRODUCT_CATEGORY = PT.PRODUCT_CATEGORY
 WHERE PC.PRIOTITY = (
 SELECT MAX(PRIOTITY) FROM PRODUCT_CATEGORIES IPC
   , PRODUCT_TYPES IPT
   WHERE IPC.PRODUCT_CATEGORY = IPT.PRODUCT_CATEGORY
     AND IPT.PRODUCTID = PT.PRODUCTID)

答案 2 :(得分:2)

select
   product_type_id,
   productid,
   product_category
from
   PRODUCT_TYPES
where
   product_type_id in (
      select
         max(product_type_id) keep (dense_rank first order by priotity desc)
      from 
         PRODUCT_TYPES
         join PRODUCT_CATEGORIES using(product_category)
      group by 
         productid
   )

SqlFiddle