2016-07-26 51 views
1

這個問題繼續從The SQL result is inaccurate because of wrong SQL date comparison setting如何準確選擇A和B之間的日期?

我在Excel中的Excel VBA使用ADO運行SQL的討論,並將結果顯示在Excel工作表。

有一個在工作表中的所謂的 「日期」 字段2014,2015,2016,2017

數據例如:2/1/2014,7/1/2014,23 /二千零十四分之十

此字段數據類型是在日/月/年,日期由= 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 month=3 and year=2016 

這是OKAY。

然後,我試着用下面的這些語句。他們不是好的。

where date >= #2016-03-01# AND date<#2016-04-01# 

where date between #2016-03-01# and #2016-04-01#

然後,我相信這應該是日期數據類型問題,Excel或VBA。

於是,我試着做下面這些測試:

對於Excel,原始數據類型是日期。我更改爲字符串,數字,一般...不好

Date sample: 6/1/2016 
String sample: 42375 
Numeric sample: 42375.00 

對於VBA,我試圖交換月份和日期。 - >#2016年1月3日#還是不行

更多信息可以參考The SQL result is inaccurate because of wrong SQL date comparison setting

回答

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,用戶或系統不會對月份字段產生混淆。

+0

'和日期> =#01/March/2016 00:00:00#和日期<#01/Apr/2016 00:00:00#'我試圖在hardcode中測試。結果並不相關 – Monchhichi

相關問題