Question

Im trying to filter results by a specific date but when I use the below code I only get results where CloseDate matches current date. It doesnt include the results from ResolvedDate when CloseDate is Null. I tried with :

(CASE WHEN (Closedate IS Null) then ResolvedDate, ELSE CloseDate END) AS FinalDate

but then it states:

 "column FinalDate does not exist"

Any other way I can do this?

Here is the code thus far. Appreciate your help.

SELECT
id,
(CASE WHEN (Closedate IS Null) then ResolvedDate, ELSE CloseDate END),
FROM cases
WHERE (EXTRACT (month FROM Closedate) = EXTRACT(month FROM current_date))
AND  ( EXTRACT(day from Closedate) = EXTRACT(day FROM current_date)) 
Was it helpful?

Solution 2

You should use COALESCE function http://www.postgresql.org/docs/current/static/functions-conditional.html

Try this:

SELECT
  id,
  COALESCE(CloseDate, ResolvedDate) AS FinalDate
FROM
  cases
WHERE
  (EXTRACT (month FROM COALESCE(CloseDate, ResolvedDate)) = EXTRACT(month FROM current_date)) AND
  (EXTRACT (day from COALESCE(CloseDate, ResolvedDate)) = EXTRACT(day FROM current_date))

That should do it...

OTHER TIPS

Assuming you want to match the year as well:

SELECT id, COALESCE(Closedate, ResolvedDate) AS cdate
FROM   cases
WHERE  date_trunc('day', COALESCE(Closedate, ResolvedDate))
     = date_trunc('day', now())

Per documentation: COALESCE, date_trunc()

If you want to ignore the year:

WHERE  to_char(COALESCE(Closedate, ResolvedDate), 'MMDD')
     = to_char(now(), 'MMDD')

A bit more on that:
How do you do date math that ignores the year?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top