1

我有一个 ms access 2010 数据库,其中包含两个不相关的表:Days 和 Periods。像这些:

Days
-----
Day (Date)
Value (Integer)

Periods
-----
PeriodNum (Integer)
StartDate (Date)
EndDate (Date)

我想得到一个新表,如下所示:

Periods_Query
-----
PeriodNum (Integer)
Value (Integer) - sum of all Values from table Days, where Day is in between 
                  StartDate and EndDate

我试图构建一个 SQL 查询,但我不知道如何获取范围。尝试过这样的事情,但没有奏效:

SELECT Period, Sum(Value) FROM Days, Periods;

那么,有没有办法构建这样的查询?

谢谢。

4

3 回答 3

1

从一个简单的SELECT查询开始,根据需要整合基础数据。

SELECT d.Date, d.Value, p.[Period #], p.StartDate, p.EndDate
FROM Days AS d, Periods AS p
WHERE d.Date BETWEEN p.StartDate AND p.EndDate;

然后转换为聚合 ( GROUP BY) 查询以计算总和。

SELECT p.[Period #], Sum(d.Value) AS SumOfValue
FROM Days AS d, Periods AS p
WHERE d.Date BETWEEN p.StartDate AND p.EndDate
GROUP BY p.[Period #];

我的印象是您可能希望将该结果集存储在另一个表中。但是,您可能会认为这是不必要的,因为您可以在使用另一个表的任何地方使用该查询。但是,如果您确实需要存储结果集,则可以转换为INSERT查询。

INSERT INTO Periods_Query(PeriodNum, [Value])
SELECT p.[Period #], Sum(d.Value) AS SumOfValue
FROM Days AS d, Periods AS p
WHERE d.Date BETWEEN p.StartDate AND p.EndDate
GROUP BY p.[Period #];
于 2013-05-27T17:44:11.203 回答
0

Another approach would be to use SUM over subselect (Tested in Access 07):

SELECT Periods.PeriodNum, Periods.StartDate, Periods.EndDate, (SELECT SUM(DayValue) FROM Days WHERE Day BETWEEN Periods.StartDate AND Periods.EndDate) AS DaySums FROM Periods;

于 2013-05-27T18:01:26.183 回答
0

创建表后,清空,

运行以下插入语句:

 Insert Periods_Query(PeriodNum, SumValues)
 Select p.PeriodNum, Sum(d.Value)
 From Periods p
    Join Days d On 
       d.Day Between p.StartDate And p. EndDate
 Group By p.PeriodNum
于 2013-05-27T17:39:15.877 回答