2013-05-22 30 views
0

我有一個表interest_summary表有兩列地區:如何尋找到總的銷售超過了60%

  • int_rate號,
  • total_balance

例如

10.25 50 
10.50 100 
10.75 240 
11.00 20 

我的查詢應該返回2列或像10.50這樣的字符串到10.75因爲加總數超過總量的60%加起來

你能提出一個Oracle的邏輯嗎?

回答

2
select 
    min(int_rate), 
    max(int_rate) 
from 
    (
    select 
     int_rate, 
     nvl(sum(total_balance) over(
     order by total_balance desc 
     rows between unbounded preceding and 1 preceding 
    ),0) as part_sum 
    from interest_summary 
) 
where 
    part_sum < (select 0.6*sum(total_balance) from interest_summary) 

fiddle

1

我假設你選擇基於以下算法行:

  1. 排序的列由total_balance(降序)
  2. 選擇最高total_balance剩餘行數
  3. 如果其total_balance添加到總餘額的運行總額低於60%,則將其添加到池中並獲得下一行(步驟2)
  4. 如果不將該行添加到池並返回。

排序後的運行總看起來像這樣(我將編號行,使其更容易理解發生了什麼):

SQL> WITH data AS (
    2   SELECT 1 id, 10.25 interest_rate, 50 total_balance FROM DUAL 
    3 UNION ALL SELECT 2 id, 10.50 interest_rate, 100 total_balance FROM DUAL 
    4 UNION ALL SELECT 3 id, 10.75 interest_rate, 240 total_balance FROM DUAL 
    5 UNION ALL SELECT 4 id, 11.00 interest_rate, 20 total_balance FROM DUAL 
    6 ) 
    7 SELECT id, interest_rate, 
    8   SUM(total_balance) OVER (ORDER BY total_balance DESC) running_total, 
    9   SUM(total_balance) OVER (ORDER BY total_balance DESC) 
10  /
11   SUM(total_balance) OVER() * 100 pct_running_total 
12 FROM data 
13 ORDER BY 3; 

     ID INTEREST_RATE RUNNING_TOTAL PCT_RUNNING_TOTAL 
---------- ------------- ------------- ----------------- 
     3   10,75   240 58,5365853658537 
     2   10,5   340 82,9268292682927 
     1   10,25   390 95,1219512195122 
     4   11   410    100 

因此,在這個例子中,我們必須返回行3和2,因爲行2是第一行的地方跑%的總在60%以上:

SQL> WITH data AS (
    2   SELECT 1 id, 10.25 interest_rate, 50 total_balance FROM DUAL 
    3 UNION ALL SELECT 2 id, 10.50 interest_rate, 100 total_balance FROM DUAL 
    4 UNION ALL SELECT 3 id, 10.75 interest_rate, 240 total_balance FROM DUAL 
    5 UNION ALL SELECT 4 id, 11.00 interest_rate, 20 total_balance FROM DUAL 
    6 ) 
    7 SELECT ID, interest_rate 
    8 FROM (SELECT ID, interest_rate, 
    9     SUM(over_limit) 
10     OVER(ORDER BY total_balance DESC) over_limit_no 
11   FROM (SELECT id, 
12       interest_rate, 
13       total_balance, 
14       CASE 
15       WHEN SUM(total_balance) 
16         OVER(ORDER BY total_balance DESC) 
17        /SUM(total_balance) OVER() * 100 < 60 THEN 
18        0 
19       ELSE 
20        1 
21       END over_limit 
22     FROM data 
23     ORDER BY 3)) 
24 WHERE over_limit_no <= 1; 

     ID INTEREST_RATE 
---------- ------------- 
     3   10,75 
     2   10,5 
+0

非常感謝您對我們的支持 –

+0

一個很好的「謝謝」,也是給予好評。我的+1,文森特,爲你的努力! –