如何获取给定日期介于 PostgreSql 中同一列的两个日期之间的记录
how to get record for which given date falls between two dates of same column in PostgreSql
我的 table 有数据,例如empcode 指定代码和晋升日期,我想获得某个给定日期的员工指定。例如
EmpCode DesignationCode PromotionDate
101 50 2010-01-25
101 10 2014-01-01
101 11 2015-01-01
102 10 2009-10-01
103 15 2015-01-01
现在,如果我检查 2014-02-01 的指定,它应该给出如下结果
EmpCode DesignationCode PromotionDate
101 10 2014-01-01
102 10 2009-10-01
谁能告诉我应该写什么查询?
提前致谢。
你可以试试:
SELECT DISTINCT ON (EmpCode) EmpCode, DesignationCode, PromotionDate
FROM mytable
WHERE PromotionDate <= '2014-02-01'
ORDER BY EmpCode, PromotionDate DESC
查询首先过滤掉任何 PromotionDate
超过给定日期的记录,即 '2014-02-01'
。
使用 DISTINCT ON
(EmpCode)
我们每个 EmpCode
得到一行。这是具有最新 PromotionDate
的那个(这是通过将 PromotionDate DESC
放在 ORDER BY
子句中实现的)。
我的 table 有数据,例如empcode 指定代码和晋升日期,我想获得某个给定日期的员工指定。例如
EmpCode DesignationCode PromotionDate 101 50 2010-01-25 101 10 2014-01-01 101 11 2015-01-01 102 10 2009-10-01 103 15 2015-01-01
现在,如果我检查 2014-02-01 的指定,它应该给出如下结果
EmpCode DesignationCode PromotionDate 101 10 2014-01-01 102 10 2009-10-01
谁能告诉我应该写什么查询?
提前致谢。
你可以试试:
SELECT DISTINCT ON (EmpCode) EmpCode, DesignationCode, PromotionDate
FROM mytable
WHERE PromotionDate <= '2014-02-01'
ORDER BY EmpCode, PromotionDate DESC
查询首先过滤掉任何 PromotionDate
超过给定日期的记录,即 '2014-02-01'
。
使用 DISTINCT ON
(EmpCode)
我们每个 EmpCode
得到一行。这是具有最新 PromotionDate
的那个(这是通过将 PromotionDate DESC
放在 ORDER BY
子句中实现的)。