此问题继续The SQL result is inaccurate because of wrong SQL date comparison setting
的讨论我在excel-VBA中使用ADO在excel中运行SQL,结果显示在excel工作表上。
有一个名为" Date"在工作表2014,2015,2016,2017
数据示例:2/1 / 2014,7 / 1 / 2014,23 / 10/2014
此字段数据类型以天/月/年为单位,日期由= DATE(cell1,cell2,cell3)组合 - 年,月,日。表中的日期应该都是纯粹的日期,因为我将3个单元格(年,月,日)合并为1个字段(日期)
现在,我想设置fromdate和todate之间的日期范围(包括两者)
' This SQL select the date between date-VARIABLE: fromdate & toDate
WHERE date >= #" & fromdate & "# AND date<#" & toDate & "#"
这里的完整SQL:
SELECT officer ,NULL, SUM(IIF( isnumeric(mkt) = true and Survey='CPI' and Activity='FI' and Outcome= 'C', Totalmin, 0 )/468) , SUM(IIF( isnumeric(Non) = true and Survey='CPI' and Activity='FI' and Outcome= 'C', Totalmin, 0 )/468) ,NULL ,NULL , IIF(ISNULL(sum(mkt)),0,sum(mkt)),Sum(Non),sum(ICP),(sum(mkt)+Sum(Non)+sum(ICP) ) ,NULL,NULL,NULL,count(IIF( Survey='CPI' and Activity='FI' ,Totalmin, NULL )),NULL,count(IIF( Survey='CPI' and Activity='FI' and (Outcome ='C' OR Outcome='D'OR Outcome='O') , Totalmin, NULL )),NULL,SUM(IIF( Survey='CPI' and Activity='FI' ,Totalmin, 0 )),NULL,SUM(IIF( Survey='CPI' and Activity='FI' and (Outcome ='C' OR Outcome='D') ,Totalmin, 0 ))
From (
select officer ,rank ,year ,month ,day , survey ,activity ,outcome ,mkt,non,totalmin,ICP ,date
from [2014$]
UNION ALL
select officer ,rank ,year ,month ,day , survey ,activity ,outcome ,mkt,non,totalmin,ICP ,date
from [2015$]
UNION ALL
select officer ,rank ,year ,month ,day , survey ,activity ,outcome ,mkt,non,totalmin,ICP ,date
from [2016$]
UNION ALL
select officer ,rank ,year ,month ,day , survey ,activity ,outcome ,mkt,non,totalmin,ICP ,date
from [2017$]
)as table3
where officer is not null and officer <> '' and officer <> ' '
and date >= #" & fromDate & "# AND date<#" & toDate & "#"
group by officer
然后我发现SQL结果正常,但结果不准确。
后来,我尝试在硬编码中测试。例如,我尝试在2016年3月选择记录。使用where where子句:
where month=3 and year=2016
好的。
然后,我尝试使用下面这些语句。他们不是好的。
where date >= #2016-03-01# AND date<#2016-04-01#
where date between #2016-03-01# and #2016-04-01#
然后,我认为它应该是excel或VBA中的日期数据类型问题。
然后,我尝试在下面进行这些测试:
对于Excel,原始数据类型为date。我改为字符串,数字,一般......不行
Date sample: 6/1/2016
String sample: 42375
Numeric sample: 42375.00
对于VBA,我试图交换月和日。 - &GT; #2016-01-03#还不行
更多信息可参考The SQL result is inaccurate because of wrong SQL date comparison setting
答案 0 :(得分:0)
尝试两件事
对于fromDate
后缀,时间点为零,toDate
后缀为时间点,指向日期结束。
fromDate = 01/01/2016 00:00:00
toDate = 02/02/2016 23:59:59
另外,如果可能的话,将月份作为3个字母的选项,我现在在我的所有工作中使用它,因为很多都会转到美国,他们做MM / DD / YYYY而不是我在英国使用DD / MM / YYYY。通过输出01 / Jan / 2016,用户或系统对月份字段没有混淆。