【问题标题】:PostgreSQL: How to join two tables using between date?PostgreSQL:如何使用日期之间连接两个表?
【发布时间】:2017-01-19 06:27:39
【问题描述】:

我真的不知道怎么问这个问题。

我将使用我需要加入的两个表来说明它。

TABLE_1

Name    Date
John    01-01-2016
May     04-08-2015
Rose    10-25-2016
Mary    12-15-2015
Ruby    07-07-2017

表_2

Signatory       DateFrom    DateTo
President 1     01-01-2015  12-31-2015
President 2     01-01-2016  12-31-2016

结果:

Name    Date        Signatory
John    01-01-2016  President 2
May     04-08-2015  President 1
Rose    10-25-2016  President 2
Mary    12-15-2015  President 1
Ruby    07-07-2017  NULL

我只需要检查 Table_1Date 是否在 Table_2 的 DateFromDateTo 内获取 Signatory 字段。

我该怎么做?

非常感谢! ^_^

【问题讨论】:

标签: sql postgresql


【解决方案1】:

试试这个:

SELECT t1.*, t2.Signatory
FROM Table_1 AS t1
LEFT JOIN Table_2 AS t2 
   ON t1."Date" BETWEEN t2.DateFrom AND t2.DateTo

您只需要在ON 子句中加上BETWEENLEFT JOIN,以确定Table_1Date 字段是否在[DateFrom, DateTo] 的任何[DateFrom, DateTo] 区间内。

Demo here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多