简体   繁体   中英

postgres sql - generate_series for date - how to do a WHERE condition on the date (has timezone)

I'ved got a postgres SQL query below on a generate_series of dates (with timezone since I want it timezone specific), and I would like to put a WHERE condition to filter based on a specific date. I have attempted with the following WHERE statement and it fails.

where d::date = "2020-11-21"

You can also test it out here my query - https://dbfiddle.uk/?rdbms=postgres_13&fiddle=b62dcd5f867a352645c0b2944a32a010

SELECT 
     d::date  AT TIME ZONE 'Asia/Tokyo' AS created_date,  
     e.id,  
     e.name,
     e.division_id,
     MIN(a.created_at) FILTER (WHERE a.activity_type = 1) as min_time_in,
     MAX(a.created_at) FILTER (WHERE a.activity_type = 2) as max_time_out
FROM    (SELECT MIN(created_at), MAX(created_at) FROM attendance) AS r(startdate,enddate)
  , generate_series(
        startdate::timestamp, 
        enddate::timestamp, 
        interval '1 day') g(d)
    CROSS JOIN  employee e
    LEFT JOIN   attendance a ON a.created_at::date = d::date AND e.id = a.employee_id
    where d::date = "2020-11-21" <--- this is an error, how do I query on a specific date
GROUP BY 
    created_date
  , e.id
  , e.name
  , e.division_id
ORDER BY 
    created_date
  , e.id;

it complaints:

ERROR:  column "2020-11-21" does not exist
LINE 15:     where d::date = "2020-11-21"

Double quotes stand for identifiers, while what you want is a literal date. You can phrase this using a standard literal date:

where d::date = date '2020-11-21'

Or with a Postgres cast:

where d::date = '2020-11-21'::date

If d has no time component, casting it is not necessary:

where d = date '2020-11-21'

And event if it does, you can still avoid the cast with a half-open filter:

where d >= date '2020-11-21' and d < date '2020-11-21' + interval '1 day'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM