开发者

SQL funky time duration query

Ok here is some example data and the expected results I would like:

  • 2011-06-26 17:07:38-04 <-- Start Date
  • 2011-10-01 00:00:00-04 <-- Wanted Date
  • 91 <-- Duration in days

  • 2011-06-25 20:08:46-04 <-- Start Date

  • 2011-09-01 00:00:00-04 <-- Wanted Date
  • 62 <-- Duration in days

Here are the conditions:

  • If t开发者_开发百科he day the 1st to the 25th, add two months plus how many days until the next first
  • If the day is the 26th till the end of the month, add three months plus how many days until the next first

Here is what I'm trying and I'm close but this seems to be doing a ton of calculations and I wanted to see if I could simplify it:

CASE
    WHEN (((DATE_TRUNC('month', 
        (date_field + INTERVAL '5 DAYS')) + INTERVAL '2 MONTH') - 
        (date_field + INTERVAL '5 DAYS') >= 62) AND 
        ((DATE_TRUNC('month', (date_field + INTERVAL '5 DAYS')) + 
        INTERVAL '2 MONTH') - (date_field + INTERVAL '5 DAYS') <= 92))
    THEN (DATE_TRUNC('month', 
        (date_field + INTERVAL '5 DAYS')) + INTERVAL '2 MONTH')
    ELSE (DATE_TRUNC('month', 
        (date_field + INTERVAL '5 DAYS')) + INTERVAL '3 MONTH')
END


select 
    case 
        when extract(day from date_field) <= 25 
        then date_trunc('month', date_field + interval '3 months')
        else date_trunc('month', date_field + interval '4 months')
    end
from t


I think your logic check and your actual math is backward. Given your requirements, it should look closer to this:

CASE WHEN EXTRACT(DAY FROM date_field) BETWEEN 1 AND 25
     THEN (date_field - EXTRACT(DAY FROM date_field):: int + 1 + INTERVAL '3 MONTH')
     ELSE (date_field - EXTRACT(DAY FROM date_field):: int + 1  + INTERVAL '4 MONTH') END

Please note that I do not have the requisite server type to test this against, but this seems to be correct.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜