简体   繁体   English

从日期访问数据库查询以使用月份

[英]Access database query for using month from a date

I have the following table schema in acess (2007). 我在Acess(2007)中具有以下表模式。

Date eventDate bit(boolean) lunch, bit(boolean) snacks, bit(boolean) Tea, 日期事件日期(布尔值)午餐,零食(布尔值),零食(布尔值)茶,

I would like to have a single query that gives count of luch, snacks and tea (each as a column) for a given month (using the eventdate). 我想有一个查询,可以给出给定月份(使用eventdate)的午餐,零食和茶(每列)的计数。

Thanks for help. 感谢帮助。

In Access, True is -1 and False is 0. So you can use the absolute value of the sum of those values to indicate how many were True. 在Access中,True为-1,False为0。因此,您可以使用这些值之和的绝对值来表示有多少是True。

SELECT Abs(Sum(lunch)) AS SumofLunch, Abs(Sum(snacks)) AS SumofSnacks, Abs(Sum(Tea)) AS SumofTea
FROM YourTable
WHERE eventDate >= #2009/08/01# And eventDate < #2009/09/01#;

Try: 尝试:

SELECT SUM(ABS(lunch)) AS lunchCount, SUM(ABS(snacks)) AS snackCount, SUM(ABS(tea)) AS teaCount
FROM <TableName>
WHERE eventDate >= #1/1/2009# AND eventDate < #2/1/2009#

I'd attack this in access using IIF statements (think like CASE statements in other databases). 我会使用IIF语句(就像其他数据库中的CASE语句一样)在访问中进行攻击。 IIF in Access returns a value when the specified condition is true (after the first comma) or another value if it evaluates to false (after the second comma). 当指定条件为true(在第一个逗号之后)时,Access中的IIF返回一个值;如果指定条件为false(在第二个逗号之后),则返回另一个值。 Because you are using booleans, checking for a true condition and rolling up via an aggregate sum will do the trick for you. 因为您使用的是布尔值,所以检查真实条件并通过合计和汇总将为您解决问题。

SELECT Month(EventDate) AS TheMonth, Year(EventDate) AS TheYear, 
SUM(IIF(Lunch, 1, 0)) AS LunchCount,
SUM(IIF(Snacks, 1, 0)) AS SnackCount,
SUM(IIF(Tea, 1, 0)) AS TeaCount
FROM YourTable
GROUP BY Month(EventDate), Year(EventDate)
ORDER BY Month(EventDate), Year(EventDate)

The above query of course returns counts for all months and years however you could easily key in on a date range like below if need be. 上面的查询当然会返回所有月份和年份的计数,但是如果需要,您可以轻松键入以下日期范围。

SELECT Month(EventDate) AS TheMonth, Year(EventDate) AS TheYear, 
SUM(IIF(Lunch, 1, 0)) AS LunchCount,
SUM(IIF(Snacks, 1, 0)) AS SnackCount,
SUM(IIF(Tea, 1, 0)) AS TeaCount
FROM YourTable
WHERE EventDate BETWEEN #1/1/2009# AND #1/31/2009#
GROUP BY Month(EventDate), Year(EventDate)
ORDER BY Month(EventDate), Year(EventDate)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM