postgresqldateweekdayweekend

Only get rows based on flag for weekend / weekday / both


I have a whole bunch of tariffs, some work on weekends, some work on weekdays some on both. Sometimes I'll be querying on NOW() but sometimes I'll be querying on datetime column.

id   | Weekday | Weekend | Price
 1   | 1       | 0       | 0.04   
 2   | 0       | 1       | 0.02          

date
2020-04-15 00:00:00
2012-04-16 00:00:00

The date is from another table and is not related to the Price / days of week.

I know I can get the weekend dates by

SELECT * FROM tariff where EXTRACT(ISODOW FROM date) IN (6,7)

however I can't think of how I'd get rows that are either weekend / weekdays or both given a date.

** edit **

Updated the tables to show the dates are seperate. What I'm trying to get is the tariff that corresponds to the date in that table, whether it's on a week day or a weekend (or both but I can extrapolate that).

The weekend 1 is the tariff that is used for weekends, weekdays 1, all days is both.


Solution

  • Cannot give you a query, supply anything to query. Nor can we be sure that the columns Weekday and Weekend mean as you didn't tell us. But if we take them as boolean indicator where 1 means desired may some thing like will work for you.

        select ...
          from ...
         where ...
           and (   (weekday = 1 and weekend =1) 
                or (weekday = 1 and extract(isodow from date) not in (6,7))
                or (weekend = 1 and extract(isodow from date)    in (6,7)) 
               ) ;