如何仅根据访问中sql查询中的日期部分显示结果

时间:2016-04-28 10:23:27

标签: sql date ms-access

目前,我的查询会根据2016年的范围显示记录,并在每月视图中显示结果(Jan, Feb, March, Apr..)

SELECT Reference.source_ID AS Source, 
Sum(IIf([quote_date] Between #1/1/2016# And #12/31/2016#,1,0)) AS Total, 
Sum(IIf([quote_date] Between #1/1/2016# And #1/31/2016#,1,0)) AS Jan, 
Sum(IIf([quote_date] Between #2/1/2016# And #2/29/2016#,1,0)) AS Feb, 
Sum(IIf([quote_date] Between #3/1/2016# And #3/31/2016#,1,0)) AS Mar, 
Sum(IIf([quote_date] Between #4/1/2016# And #4/30/2016#,1,0)) AS Apr, 
Sum(IIf([quote_date] Between #5/1/2016# And #5/31/2016#,1,0)) AS May, 
Sum(IIf([quote_date] Between #6/1/2016# And #6/30/2016#,1,0)) AS June, 
Sum(IIf([quote_date] Between #7/1/2016# And #7/31/2016#,1,0)) AS July, 
Sum(IIf([quote_date] Between #8/1/2016# And #8/31/2016#,1,0)) AS Aug, 
Sum(IIf([quote_date] Between #9/1/2016# And #9/30/2016#,1,0)) AS Sept, 
Sum(IIf([quote_date] Between #10/1/2016# And #10/31/2016#,1,0)) AS Oct, 
Sum(IIf([quote_date] Between #11/1/2016# And #11/30/2016#,1,0)) AS Nov, 
Sum(IIf([quote_date] Between #12/1/2016# And #12/31/2016#,1,0)) AS [Dec]
FROM Reference
GROUP BY Reference.source_ID;

我希望添加允许用户选择日期范围的搜索表单

这会将以下参数添加到我的查询

WHERE (((Reference.quote_date) Between [Forms]![Total_Calls_by_Source_Search]![StartDateTxt] And [Forms]![Total_Calls_by_Source_Search]![EndDatetxt]))

我的问题是如何更改查询以便它可以显示2017,2018等的结果

2 个答案:

答案 0 :(得分:1)

这应该按年quote_date对所有记录进行分组,并输出该特定年份每个月的正确计数,并按表单输入进行过滤。不太清楚如何处理总线,它在那一年为每个非空记录添加1。我不确定它是否适用于GROUP BY refID。

SELECT Reference.source_ID AS Source, 
Sum(IIf(ISNULL([quote_date]),0,1)) AS Total, 
Sum(IIf(Month([quote_date])=1,1,0)) AS Jan, 
Sum(IIf(Month([quote_date])=2,1,0)) AS Feb, 
Sum(IIf(Month([quote_date])=3,1,0)) AS Mar, 
Sum(IIf(Month([quote_date])=4,1,0)) AS Apr, 
Sum(IIf(Month([quote_date])=5,1,0)) AS May, 
Sum(IIf(Month([quote_date])=6,1,0)) AS June, 
Sum(IIf(Month([quote_date])=7,1,0)) AS July, 
Sum(IIf(Month([quote_date])=8,1,0)) AS Aug, 
Sum(IIf(Month([quote_date])=9,1,0)) AS Sept, 
Sum(IIf(Month([quote_date])=10,1,0)) AS Oct, 
Sum(IIf(Month([quote_date])=11,1,0)) AS Nov, 
Sum(IIf(Month([quote_date])=12,1,0)) AS Dec
FROM Reference
WHERE (((Reference.quote_date) Between [Forms]![Total_Calls_by_Source_Search]![StartDateTxt] 
  And [Forms]![Total_Calls_by_Source_Search]![EndDatetxt]))
GROUP BY Reference.source_ID, YEAR([quote_date]);

答案 1 :(得分:0)

您可以使用year作为参数:

Sum(IIf([quote_date] Between DateSerial([year],2,1) And DateSerial([year],2+1,0),1,0)) AS Feb, 

同样是其他11个月。