我需要在访问数据库中使用 SQL 获取今年旅行的总里程数。目前我正在尝试以下查询,但它不起作用:
SELECT
SUM(Mileage)
FROM
[Mileage-Expenses]
WHERE
YEAR(DatePurchased) = YEAR(CURRENT_TIMESTAMP)
任何想法如何解决这一问题?
A WHERE
clause based on YEAR(DatePurchased)
requires the db engine evaluate that expression for every row in the table. You would get better performance by adding an index on DatePurchased
, if you don't already have one, and then using a WHERE
clause which allows the db engine to retrieve only the rows from the current year before computing SUM(Mileage)
.
SELECT
SUM(Mileage)
FROM
[Mileage-Expenses]
WHERE
DatePurchased >= DateSerial(Year(Date()), 1, 1)
AND DatePurchased < DateSerial(Year(Date()) + 1, 1, 1)
我已经很久没有使用 MS Access 了,但据我记得它不支持CURRENT_TIMESTAMP
,你需要使用DATE()
orNOW()
代替:
SELECT
SUM(Mileage)
FROM
[Mileage-Expenses]
WHERE
YEAR(DatePurchased) = YEAR(DATE())