2013-10-28 45 views
0

我有以下腳本 -多個集合函數

select sum(duration) as duration from opr 
     where op in ('GRC','GCQ') 
     and timestamp between '20130101000000' and '20130930235959' 

我得到的價值 - 秒。 我想包括這些限制 - 這是持續時間

  • < = '18000000'(秒)應乘以0.14

  • '18000000' < =「27000000之間>的持續時間和'應該是 乘以0.11

  • 和持續時間> '27000000' 應乘以0.09

我試圖用這個case語句 -

case when duration <= '18000000' 
     then (duration)*0.14 
     when duration > '18000000' and duration <= '27000000' 
     then (duration)*0.11 
     when duration > '27000000' 
     then (duration)*0.09 
      else 0 end as bal 

不過,我收到此值乘以0.09,因爲它是更大然後「27000000」,這是不是主意。 這個想法是這兩個操作('​​GRC','GCQ')所做的所有秒數與上述值相乘。

你能幫我做這個嗎?

回答

3

duration一個數字或字符串?會更好地與數字進行比較,我猜:

SELECT 
    SUM(
     CASE 
     WHEN duration <= 18000000 THEN duration * 0.14 
     WHEN duration > 18000000 AND duration <= 27000000 THEN duration * 0.11 
     WHEN duration > 27000000 THEN duration * 0.09 
     ELSE 0 
     END 
    ) AS duration 
    FROM opr 
WHERE 
    op IN ('GRC','GCQ') 
    AND timestamp BETWEEN '20130101000000' AND '20130930235959' 
; 
+0

非常感謝,它的工作原理 – Kristiana

1

使用子查詢來選擇特定的持續時間並乘以您的值的持續時間,然後在該子查詢上使用求和。

1

試試這個:

select sum(case 
     when duration <= '18000000' then (duration)*0.14 
     when duration > '18000000' and duration <= '27000000' then (duration)*0.11 
     when duration > '27000000' then (duration)*0.09 
     else 0 
    end) as bal 
from opr 
where op in ('GRC','GCQ') 
    and timestamp between '20130101000000' and '20130930235959' 
1

我想你想這樣做

select sum(case when duration <= '18000000' then (duration)*0.14 
       when duration > '18000000' and duration <= '27000000' then (duration)*0.11 
       when duration > '27000000' then (duration)*0.09 
       else 0 end as bal) as duration 
from opr 
where op in ('GRC','GCQ') 
and timestamp between '20130101000000' and '20130930235959'