多个聚合函数

时间:2013-10-28 10:10:45

标签: sql database plsql

我有以下脚本 -

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

我收到了值 - 34459298 秒。 我想包括这些限制 - 持续时间

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

  • >之间的持续时间' 18000000'和< =' 27000000'应该 乘以0.11

  • 并且持续时间> ' 27000000'应该乘以0.09

我试过这个案例陈述 -

   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

但是,我收到此值 34459298 乘以0.09,因为它大于&#39; 27000000&#39;,这不是主意。 这个想法是这两个操作(&#39; GRC&#39; GCQ&#39;)与上述值相乘的所有秒数。

你能帮我做一下吗?

4 个答案:

答案 0 :(得分: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'
;

答案 1 :(得分:1)

使用子查询选择特定的持续时间,并按照您的值乘以持续时间,然后使用该子查询的总和。

答案 2 :(得分: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'

答案 3 :(得分: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'