Oracle Complex Sort - 多个孩子

时间:2012-05-15 15:29:07

标签: sql oracle10g

我有一张表格如下:

BRAND_ID PRODUCT_ID PRODUCT_DESC PRODUCT_TYPE
100      1000       Tools        A
100      1500       Tools        A 
200      2000       Burgers      B
300      3000       Clothing     C
300      4000       Makeup       D
300      5000       Clothing     C

因此,品牌可以拥有多种产品,所有产品都是相同类型或混合类型。如果一个品牌的产品都是同一类型,我首先在结果中需要它们,按产品类型排序,然后是具有不同产品类型的品牌。我可以以编程方式执行此操作,但我想查看是否有办法在查询中执行此操作。

2 个答案:

答案 0 :(得分:1)

我无法访问Oracle,但我相信这些内容应该有效......

WITH
  ranked_data
AS
(
  SELECT
    COUNT(DISTINCT product_type) OVER (PARTITION BY brand_id)  AS brand_rank,
    MIN(product_type)            OVER (PARTITION BY brand_id)  AS first_product_type,
    *
  FROM
    yourTable
)
SELECT
  *
FROM
  ranked_data
ORDER BY
  brand_rank,
  first_product_type,
  brand_id,
  product_type,
  product_description


另一种方法是加入子查询以计算两个排序字段。

SELECT
  yourTable.*
FROM
  yourTable
INNER JOIN
(
  SELECT
    brand_id,
    COUNT(DISTINCT product_type) AS brand_rank,
    MIN(product_type)            AS first_product_type,
  FROM
    yourTable
  GROUP BY
    brand_id
)
  AS brand_summary
    ON yourTable.brand_id = brand_summary.brand_id
ORDER BY
  brand_summary.brand_rank,
  brand_summary.first_product_type,
  yourTable.brand_id,
  yourTable.product_type,
  yourTable.product_description

答案 1 :(得分:1)

如何选择能够计算出不同品牌数量的子选择,然后按计数排序?

select t.BRAND_ID, 
       t.PRODUCT_ID, 
       t.PRODUCT_DESC, 
       t.PRODUCT_TYPE
  from (select t2.BRAND_ID, 
               t2.PRODUCT_ID, 
               count(distinct t2.PRODUCT_TYPE) cnt
          from YOURTABLE t2
         group by t2.BRAND_ID, t2.PRODUCT_ID) data
  join YOURTABLE t on t.BRAND_ID = data.BRAND_ID and t.PRODUCT_ID = data.PRODUCT_ID
 order by data.cnt, BRAND_ID, PRODUCT_ID, PRODUCT_TYPE