记一次常识性错误——SQL中使用between过滤日期的使用错误

2021/12/14 19:20:27

本文主要是介绍记一次常识性错误——SQL中使用between过滤日期的使用错误,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

要求

查询出11月份的数据

错误语句

select DISTINCT 
C.kingdee_sku_name ,--物料名称
SUM( B.tzzl) OVER(PARTITION BY SUBSTRING(B.sku_bj,7,2)) ,---重量
SUM(B.sl)   OVER(PARTITION BY SUBSTRING(B.sku_bj,7,2)) --支数
from
	ERP_SCjh_zzc_pl_ck A 
inner join erp_scjh_zzc_plmx_ck B on  A.djno =B.djno  AND A.djlb = B.djlb 
LEFT  JOIN kingdee_sku_detail C ON C.kingdee_sku_no  =B.sku_bj 
where
	A.djlb = 'xxx'
	AND A.ifendor ='已审核'
	and a.endor_date BETWEEN '2021-11-01' and '2021-11-30'

分析

错误地方:a.endor_date BETWEEN '2021-11-01' and '2021-11-30'
endor_date这个字段是年月日时分秒的格式,BETWEEN在SQL SERVER中是左右包含,上述错误语句查询出的是2021-11-01 至 2021-11-30 00:00:00 的数据,而需求要求的是11月整月的数据,其中缺少了30日这天的,可以将以上语句修改为下述语句。

正确语句

select DISTINCT 
C.kingdee_sku_name ,--物料名称
SUM( B.tzzl) OVER(PARTITION BY SUBSTRING(B.sku_bj,7,2)) ,---重量
SUM(B.sl)   OVER(PARTITION BY SUBSTRING(B.sku_bj,7,2)) --支数
from
	ERP_SCjh_zzc_pl_ck A 
inner join erp_scjh_zzc_plmx_ck B on  A.djno =B.djno  AND A.djlb = B.djlb 
LEFT  JOIN kingdee_sku_detail C ON C.kingdee_sku_no  =B.sku_bj 
where
	A.djlb = 'xxx'
	AND A.ifendor ='已审核'
	and format(a.endor_date,'yyyy-MM-dd') BETWEEN '2021-11-01' and '2021-11-30'

其中将日期进行了一次转换为年-月-日的格式,那么30日就包含在between范围内了,或者直接使用大于,小于介于范围内。

select DISTINCT 
C.kingdee_sku_name ,--物料名称
SUM( B.tzzl) OVER(PARTITION BY SUBSTRING(B.sku_bj,7,2)) ,---重量
SUM(B.sl)   OVER(PARTITION BY SUBSTRING(B.sku_bj,7,2)) --支数
from
	ERP_SCjh_zzc_pl_ck A 
inner join erp_scjh_zzc_plmx_ck B on  A.djno =B.djno  AND A.djlb = B.djlb 
LEFT  JOIN kingdee_sku_detail C ON C.kingdee_sku_no  =B.sku_bj 
where
	A.djlb = 'xxx'
	AND A.ifendor ='已审核'
	and a.endor_date >= '2021-11-01' and a.endor_date <'2021-12-01'


这篇关于记一次常识性错误——SQL中使用between过滤日期的使用错误的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程