我正在开发一个拥有MS Access数据库的项目。它的结构类似于:
some id
m1(stands for month 1 jan)
m2(stands for month 2 feb)
.
.
m12( stands for month 12 dec)
year
现在要检索今年的数据我可以写
Select * from tbl where id=123 and year=2016
但我不想要一年的数据。假设它现在是七月,所以我想要从去年6月(2015年)到6月(2016年)的数据。我们怎么做?现在我在两个查询中找到结果,然后使用if else合并它。
答案 0 :(得分:1)
这在Access 2010中似乎对我有用:
SELECT *
FROM
(
SELECT DateSerial([year], 1, 1) AS MonthStart, [m1] AS TheValue FROM tbl
UNION ALL
SELECT DateSerial([year], 2, 1) AS MonthStart, [m2] AS TheValue FROM tbl
UNION ALL
SELECT DateSerial([year], 3, 1) AS MonthStart, [m3] AS TheValue FROM tbl
UNION ALL
SELECT DateSerial([year], 4, 1) AS MonthStart, [m4] AS TheValue FROM tbl
UNION ALL
SELECT DateSerial([year], 5, 1) AS MonthStart, [m5] AS TheValue FROM tbl
UNION ALL
SELECT DateSerial([year], 6, 1) AS MonthStart, [m6] AS TheValue FROM tbl
UNION ALL
SELECT DateSerial([year], 7, 1) AS MonthStart, [m7] AS TheValue FROM tbl
UNION ALL
SELECT DateSerial([year], 8, 1) AS MonthStart, [m8] AS TheValue FROM tbl
UNION ALL
SELECT DateSerial([year], 9, 1) AS MonthStart, [m9] AS TheValue FROM tbl
UNION ALL
SELECT DateSerial([year], 10, 1) AS MonthStart, [m10] AS TheValue FROM tbl
UNION ALL
SELECT DateSerial([year], 11, 1) AS MonthStart, [m11] AS TheValue FROM tbl
UNION ALL
SELECT DateSerial([year], 12, 1) AS MonthStart, [m12] AS TheValue FROM tbl
)
WHERE
MonthStart
BETWEEN
DateSerial(Year(Date()) - 1, Month(Date()), 1)
AND
DateSerial(Year(Date()), Month(Date()) - 1, 1)
ORDER BY MonthStart
UNION ALL子查询“unpivots”数据,WHERE子句隔离前12个月的结果。
答案 1 :(得分:0)
只需使用
Where (month in (6,7,8,9,10,11,12) and year=2015) or (month in (1,2,3,4,5,6) and year=2016) and ID=123
编辑:您可以使用
Where (month in (x to 12) and year=y) or (month in (1 to x) and year=y+1)
x是您想要的月份,y是开始年份
第二次编辑:我不知道(x to y)
是否可以在访问中使用,以便您更好地使用
Where (month (Between x and 12) and year=y) or ((month Between 1 and x) and year=y+1)