【问题标题】:postgresql case when date and sorting by date日期和按日期排序时的postgresql案例
【发布时间】:2014-03-10 22:26:03
【问题描述】:

我试图按特定日期过滤结果,但是当我使用下面的代码时,我只会得到 CloseDate 与当前日期匹配的结果。当 CloseDate 为 Null 时,它不包括 ResolvedDate 的结果。 我试过了:

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

然后它声明:

 "column FinalDate does not exist"

还有其他方法可以做到吗?

这是目前为止的代码。感谢您的帮助。

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)) 

【问题讨论】:

  • 有了你的 where 子句,因为它是 CloseDate 无论如何都不能为空。但是,您可以只使用COALESCE(CloseDate, ResolvedDate)。如果你做了类似CloseDate >= current_date AND CloseDate < current_date + interval 1 day'` 之类的事情,这也将是一个更有意义的查询
  • ResolveDate 之后删除逗号..除非 postgres 像那样奇怪。
  • 表定义将符合这样的问题。我们需要准确的数据类型。
  • 嗨,我在多余的逗号上弄错了,它不应该在那里。
  • 您不能在 where 子句中引用列别名,您需要重复表达式,或者将表达式放在子查询中,然后应用 where 子句。

标签: sql postgresql case


【解决方案1】:

假设您也想匹配年份:

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

根据文档:COALESCE、date_trunc()

如果你想忽略年份:

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

更多信息:
How do you do date math that ignores the year?

【讨论】:

  • 谢谢,但我收到一个错误:函数 date_trunc(未知,没有时区的时间戳,没有时区的时间戳)不存在
  • @exclusivebiz:这可能是我的答案的初稿有错误。您一定错过了更新,它现在可以正常工作了。
【解决方案2】:

你应该使用 COALESCE 函数http://www.postgresql.org/docs/current/static/functions-conditional.html

试试这个:

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))

应该可以的...

【讨论】:

  • 很好,很高兴能帮上忙! :-)
  • 感谢@a_horse_with_no_name 链接已过期的编辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-19
  • 2012-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-18
  • 1970-01-01
相关资源
最近更新 更多