TSQL - 匹配另一个表中两个日期之间的日期

时间:2021-03-02 22:31:52

标签: sql-server tsql

我目前有两个表,tbl_Invoices

InvoiceNumber  NextBillingDate
------------------------------
    100            3/15/21
    200            3/31/21
    300            4/15/21
    400            5/15/21

tbl_GLPeriods

GLPeriod     PeriodStartDate     PeriodEndDate
----------------------------------------------
  250            3/3/21              4/3/21
  251            4/4/21              5/2/21
  252            5/3/21              6/3/21

我需要一个视图来返回一个列,其中提供了下一个帐单日期的 GL 期间,即:

InvoiceNumber  NextBillingPeriod
---------------------------------
    100              250
    200              250
    300              251
    400              252

如何查询一列是否在另一表的两列之间?我正在思考如何做到这一点,用 CASE 思考一些事情。

编辑:我目前所处的位置,从结构上来说是行不通的,但它显示了我目前正在努力的方向:

SELECT
    *,
    CASE
       WHEN tbl_Invoices.NextBillingDate BETWEEN (SELECT PeriodStartDate FROM tbl_GLPeriods) AS stdt 
                                             AND (SELECT PeriodEndDate FROM tbl_GLPeriods) AS endt  
          THEN endt.GLPeriod    
    END AS NextBillingPeriod
FROM
    tbl_Invoices

感谢@Charlieface 解决了这个问题:

select tbl_Invoices.InvoiceNumber, tbl_GLPeriods.GLPeriod 
from tbl_Invoices
left join tbl_GLPeriods on tbl_Invoices.NextBillingDate between tbl_GLPeriods.PeriodStartDate AND tbl_GLPeriods.PeriodEndDate

2 个答案:

答案 0 :(得分:0)

select InvoiceNumber, (select GLPeriod from tbl_GLPeriods where NextBillingDate between PeriodStartDate and PeriodEndDate) 'NextBillingPeriod' from tbl_Invoices

答案 1 :(得分:0)

您可以使用 AND 连接多个谓词以检查具有 <=>(或等效项)的范围。像这样,您可以使用与您尝试过的类似的相关子查询,前提是句点不能重叠。

SELECT i.invoicenumber,
       (SELECT p.glperiod
               FROM tbl_glperiods p
               WHERE p.periodstartdate <= i.nextbillingdate
                     AND dateadd(DAY, 1, p.periodenddate) > i.nextbillingdate) nextbillingperiod
       FROM tbl_invoices i;

您也可以使用左连接。然后期间可以重叠,如果日期落在两个或更多期间,您将获得多行。连接也可能性能更好。

SELECT i.invoicenumber,
       p.glperiod nextbillingperiod
       FROM tbl_invoices i
            LEFT JOIN tbl_glperiods p
                      ON p.periodstartdate <= i.nextbillingdate
                         AND dateadd(DAY, 1, p.periodenddate) > i.nextbillingdate;

请注意,您可以将 dateadd(DAY, 1, p.periodenddate) 缩短为仅 p.periodenddate,如果 tbl_glperiods.periodenddate 是唯一的上限,或者如果它是包含但保证 tbl_invoices.nextbillingdate 不会更多比一天精确,即它不能有小时、分钟、秒等部分。否则,您可能会错过最后一天午夜过后的时间戳。