首页 > 解决方案 > 当日期戳有特殊异常时如何捕获结果

问题描述

我相当确定我可以在这种情况下使用 CASE 语句,但我显然没有正确看待这个问题。

在我的 WHERE 子句中,当日期戳位于 7 月份时,我需要将归为 8 月份的结果。这是我正在尝试的,但我错过了标记:

and CPTrn_DateTime = case
        when datepart(month, CPTrn_DateTime) = 7 then datepart(month, CPTrn_DateTime) in (7,8) 

我尝试使用 CASE 语句的原因是,只有在 7 月份,我才需要将这些结果与 8 月份的结果相关联。我不能做一个简单的日期范围的原因是因为随着时间的推移,我需要为所有日期工作的逻辑。

这是整个查询:

DECLARE @month INT

SET @month = 8

SELECT DISTINCT cp.CPTrn_Key
    ,ch.Chg_Ref_No
    ,c.Cust_Alias
    ,ch.Chg_Total_Units
    ,ch.Chg_Amount
    ,cp.CPTrn_DateTime
FROM PDICompany_2049_01..CP_Transactions cp(NOLOCK)
INNER JOIN PDICompany_2049_01..Customers c(NOLOCK) ON CPTrn_Cust_Key = Cust_Key
INNER JOIN PDICompany_2049_01..Products p(NOLOCK) ON cp.CPTrn_Prod_Key = Prod_Key
LEFT JOIN PDICompany_2049_01..CP_Billing_Details CPBD(NOLOCK) ON CPBd.CPBillDtl_CPTrn_Key = cp.CPTrn_Key
    AND CPTrn_Cust_Key = CPBD.CPBillDtl_Cust_Key
    AND CPBD.CPBillDtl_Rec_Type = 1
LEFT JOIN PDICompany_2049_01..Customer_Locations cl(NOLOCK) ON c.Cust_WhPrcNtc_Def_CustLoc_Key = cl.CustLoc_Key
    AND ((CustLoc_Type & 2) <> 0)
LEFT JOIN Charges ch ON ch.Chg_Ref_No = cpbd.CPBillDtl_Invoice_No
WHERE cp.CPTrn_Tran_Type != 0
    AND c.Cust_Alias = 'MONTGOMERY CRANES, LLC'
    AND CPBillDtl_Invoice_No IS NOT NULL
    AND CPTrn_DateTime = CASE 
        WHEN datepart(month, CPTrn_DateTime) = 7
            THEN datepart(month, CPTrn_DateTime) IN (7,8)
        ELSE datepart(month, CPTrn_DateTime) = @month
        END AS 'CPTrn_DateTime'
ORDER BY 1

标签: sql-server

解决方案


这样做是一个CASE 表达式Case语句在 T-SQL 中不存在),该DATEPART函数可能会破坏性能。

您没有在 a 中“分组” WHERE,而是在您的 中这样做GROUP By,所以我正在阅读这些线路,但是“正常”日期逻辑有什么问题?

WHERE CPTrn_DateTime >= '20190701'
  AND CPTrn_DateTime < '20190901'

编辑:简单的日期逻辑仍然是您所追求的:

DECLARE @Month int = 8,
        @Year int = 2019;

DECLARE @DateStart date = DATEFROMPARTS(@Year, IIF(@Month = 8, 7, @MOnth),1);
DECLARE @DateEnd date = DATEFROMPARTS(@Year, @Month+1, 1);

SELECT ...
FROM...
WHERE CPTrn_DateTime >= @DateStart
      AND CPTrn_DateTime < @DateEnd

推荐阅读