sql-server - 当日期戳有特殊异常时如何捕获结果
问题描述
我相当确定我可以在这种情况下使用 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
解决方案
这样做是一个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
推荐阅读
- javascript - 让谷歌地图上的标记从数据库中显示的问题?
- nginx - 如何使用 nginx-buildpack 在 Cloud Foundry 中启用 HTTP2?
- java -
TestRunner [Junit] D:\Java\JDK-14.0.1\bin\javaw.exe - c++ - 非类型模板参数不能有类型
- c# - 幂和斐波那契的 C# 小数精度改进
- javascript - 在反应中动态地从集合内的firebase集合中获取数据
- prolog - 如何在prolog中返回小于或等于输入值的所有事实
- mysql - 如何对每列使用 mysql IN 函数或如何在列上使用 MAKE_SET()
- python - 有没有办法只输出这个 if 语句中的第一个元素,Django 模板?
- flutter - 是否可以监听更改,并在更改后从单独的类中获取这些新值并更新当前类中的变量?