2015-04-15 90 views
1

我正在處理一個數據集,在這個數據集中,我希望獲得每個class_rk與驅動程序SKU一起銷售的#1賣家,然後是每個class_rk中的#2賣家等.Class_rk與sold_sku關聯)已經在之前的查詢中被識別。這裏是集:SQL等級和順序

driver_sku sold_sku class_rk sold_units 
555  432   1   20 
555  235   2   17 
555  322   2   15 
555  253   1   14 
555  152   3   13 
555  732   1   9 
555  913   3   6 

我會尋找的輸出:

driver_sku sold_sku class_rk sold_units 
555  432   1   20 
555  235   2   17 
555  152   3   13 
555  253   1   14 
555  322   2   15 
555  913   3   6 
555  732   1   9 

下面是到目前爲止我試過的代碼:基於你如何

select driver_sku, sold_sku, class_rk, sold_count, 
row_number() over(partition by driver_item_id order by class_rk, sold_count desc) as rank from data_table; 
+0

哪個dbms? (並非所有產品都支持此功能。) – jarlh

+0

在hadoop中使用配置單元 – jKraut

+0

@GordonLinoff - class_rk是sold_sku的編號 – jKraut

回答

1

描述了這個問題,你似乎想分區class_rk

select driver_sku, sold_sku, class_rk, sold_count, 
     row_number() over(partition by driver_item_id, class_rk 
         order by sold_count desc 
         ) as rank 
from data_table; 

但是,這不符合預期的結果。

編輯:

根據您如何描述這個問題,你似乎想通過class_rk分區和改變order by

select t.* 
from (select driver_sku, sold_sku, class_rk, sold_count, 
      row_number() over (partition by driver_item_id, class_rk 
           order by sold_count desc 
           ) as rank 
     from data_table 
    ) t 
order by rank, class_rk 

如果你真的想一一列舉:

select t.*, 
     row_number() over (partition by driver_sku, rank 
          order by sold_count desc) as newcol 
from (select driver_sku, sold_sku, class_rk, sold_count, 
      row_number() over (partition by driver_item_id, class_rk 
           order by sold_count desc 
           ) as rank 
     from data_table 
    ) t 
order by rank, class_rk 
+0

它不會給每個class_rk頂級sold_sku,例如在class_rk#1頂級sold_sku,然後頂部sold_sku在class_rk#2等 – jKraut

+0

@jKraut。 。 。該評論有助於澄清問題。你想通過* rank *進行分區。我想我明白了。 –

0

根據你的意見,這聽起來像你只是想每個class_rk一個記錄。我認爲這可能是你要找的東西:

SELECT driver_sku, sold_sku, class_rk, max(sold_count) 
FROM <TABLE> 
GROUP BY driver_sku, class_rk 
ORDER_BY class_rk 

但是如果你想要的順序要像你的問題,我認爲你必須做這樣的事情:

with ranked as (
    SELECT driver_sku, sold_sku, class_rk, sold_count, 
     row_number() over(partition by driver_sku, class_rk order by sold_count desc) as rank 
    FROM <TABLE>  
) 

SELECT driver_sku, sold_sku, class_rk, sold_count 
FROM ranked 
GROUP BY driver_sku, rank 
ORDER BY class_rk