MS Access:我们可以在IN运算符中使用日期函数吗?

时间:2015-10-12 06:14:22

标签: sql ms-access pivot

我正在尝试从表创建交叉表查询:

ProductName | DateP    | Value |
Milk1       |1/1/2015  |      4|
Milk2       |1/1/2014  |      3|
Milk3       |1/1/2013  |      3|

以便交叉表查询结果如下所示:

ProductName | 2014 | 2015 |
Milk1       |      |    4 |
Milk2       |    3 |      |
Milk3       |      |      |

所以我的查询是:

TRANSFORM Sum(test.Value) AS Total
SELECT test.ProductName
FROM test
GROUP BY test.ProductName
PIVOT Year(test.DateP)
IN(Year(Now())-1, Year(Now())); ===> this line is the error its looking for missing parenthesis or square brackets but if I change that to IN(2014,2015) it's working fine

我想要的是年份列是动态的,最多只有2列会出现,如果我们在2016年,现在列应分别为2015年和2016年。

我希望后端部分可以解决这个问题,但如果我找不到,那么我将使用我知道的前端技巧来查询。

EDITED: 注意:ProductName' Milk3'也应该显示,也就是说,即使产品没有该年份的值也应该显示。 Gustav的解决方案几乎是正确的。

1 个答案:

答案 0 :(得分:0)

你可以这样做:

TRANSFORM Sum(test.Value) AS Total
SELECT test.ProductName
FROM test
WHERE test.DateP 
    Between DateSerial(Year(Date())-1, 1, 1) 
    And DateSerial(Year(Date()), 12, 31)
GROUP BY test.ProductName
PIVOT Year(test.DateP)

将使用DateP上的索引。

相关问题