2013-10-28 44 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'