0

I have the following script -

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

I receive the value - 34459298 seconds. I would like to include these restrictions - The duration which is

  • <= '18000000' (seconds) should be multiplied to 0.14

  • The duration between > '18000000' and <= '27000000' should be multiplied to 0.11

  • and the duration > '27000000' should be multiplied to 0.09

I have tried with this case statement -

   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

However, I receive this value 34459298 multiplied to 0.09, because it is bigger then '27000000', which is not the idea. The idea is all the seconds which these two op ('GRC','GCQ') had made to be multiplied with the above values.

Could you please help me to do this?

4 Answers 4

3

Is duration a number or a string? Would be better to compare with numbers, I guess:

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'
;
Sign up to request clarification or add additional context in comments.

Comments

1

use subquery to select specific duration and multiply duration by your values and than use sum over that subquery.

Comments

1

Try this:

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'

Comments

1

I think you want to do this

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.