簡體   English   中英

一個數據集中不同組的oracle sql select / set rownumber限制有所不同

[英]oracle sql select/set rownumber limitation differently for different group in one data set

我有一個表,該表有4列:customer,product_id,score,tag在tag列“ new”和“ old”中有2個值

對於每個客戶,每個客戶都有'new'和'old'標簽的product_id(數量各不相同),我們根據得分和標簽對product_id進行排名,我們對每個客戶的產品數量有總限制。 稱之為“ n_prod”

我希望為每個客戶從“舊”標簽中選擇(2/3 * n_prod)product_id,為“新”標簽中選擇(1/3 * n_prod)產品,例如,如果我們需要選擇6種產品,希望從“舊”標簽中選擇4種標簽(基於得分的前4名),以及“新”標簽中的2個(基於得分的前2名)

我能夠創建一個名為“ rn”的列,使用以下命令根據每個客戶和標簽對product_id進行排名

select customer, product_id, score, tag
      , row_number()over(partition by customer,tag, order by score desc) as rn 
from table

限制數量對於不同的組是不同的:嘗試過此方法,但不起作用:

with tep as
(select customer, product_id, score, tag
      , row_number()over(partition by customer,tag, order by score desc) as rn 
from table)

select tep.*
from tep
where ( case 
         when tag='new' then rn<= round(n_prod*0.33,0)
         else then rn<= round(n_prod*0.66,0)
         end
);

我可以將“ where”和“ case when”或“ if else”組合在一起嗎?

重申預期結果:我希望為每個客戶從“舊”標簽中選擇(2/3 * n_prod)product_id,為“新”標簽中選擇(1/3 * n_prod)產品,例如,如果我們需要選擇6種產品,希望4個來自“舊”標簽(基於得分排名前4位),還有2個來自“新”標簽(基於得分排名前2位)

很難確定沒有數據,但是我認為您只需要在where子句中使用布爾邏輯:

...
select tep.*
from tep
where (tag = 'new' and rn <= round(n_prod*0.33))
   or (tag = 'old' and rn <= round(n_prod*0.66));

使用另一個CTE中的一些n_prod數據進行快速演示,並將n_prod作為綁定變量:

var n_prod number;
exec :n_prod := 6;

with your_table (customer, product_id, score, tag) as (
            select 1234, 2345, level, 'old' from dual connect by level <= 10
  union all select 1234, 2345, level, 'new' from dual connect by level <= 10
),
tep as
(select customer, product_id, score, tag
      , row_number()over(partition by customer,tag order by score desc) as rn 
from your_table)
select tep.*
from tep
where (tag = 'new' and rn <= round(:n_prod*0.33))
or (tag = 'old' and rn <= round(:n_prod*0.66));

  CUSTOMER PRODUCT_ID      SCORE TAG         RN
---------- ---------- ---------- --- ----------
      1234       2345         10 new          1
      1234       2345          9 new          2
      1234       2345         10 old          1
      1234       2345          9 old          2
      1234       2345          8 old          3
      1234       2345          7 old          4

順便說一句,您可能需要增加用於n_prod較大值的n_prod 在... er ... 28之后,使用0.33和0.66時,返回的總行數開始出錯。( round(28*.33)為9; round(28*.66)為18;因此總數為27直到253,使用0.333和0.666似乎是安全的;直到2503使用0.3333和0.6666才是安全的;等等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM