Search code examples
postgresqlsas

Converting SAS IFN(), HOUR() and MINUTE() to PostgreSQL


(hour(date_column ) * 4)
+ ifn(minute(date_column ) = 0, 0
     , ifn(minute(date_column ) <= 15, 1
          , ifn(minute(date_column ) <= 30, 2
               , ifn(minute(date_column ) <= 45, 3, 4))))
 as date_no

What are the equivalents of these functions in PostgreSQL?

I am trying to extract value based on 15 mins interval in an hour.


Solution

  • It would help if you explained your goal and current logic in a bit more detail, but for now it looks like this would suffice:

    select extract('hours' from date_column) * 4 
        + ceil(extract('minutes' from date_column) / 15) as date_no
    from your_table;
    
    1. extract() is used in PostgreSQL for the same thing hour() and minute() are in SAS.
    2. You can use CASE the exact same way you would in SAS but there's no IFN() counterpart.
    3. CEIL() works the same in both, so you could also shorten your SAS version replacing all the IFN's.
    4. You're effectively binning date/times, so you could look into date_bin(). Similar effect can probably be achieved in SAS through the use of INTNX() or plain ROUND() (1, 2).

    Demo