简体   繁体   English

如何在MS Access中创建具有不相关表范围的SQL查询?

[英]How to create a sql query with ranges from unrelated table in ms access?

I have an ms access 2010 database with two unrelated tables: Days and Periods. 我有一个ms Access 2010数据库,其中包含两个不相关的表:天和期间。 Like these: 像这些:

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

and

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

I want to get a new table, like this: 我想要一个新表,像这样:

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

I tried to build an SQL query, but i don't know how to get ranges. 我试图建立一个SQL查询,但我不知道如何获取范围。 Tried somethig like this but it didn't work: 试过这样的东西,但是没有用:

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

So, is there a way to build such a query? 那么,有没有办法建立这样的查询?

Thanks. 谢谢。

Start with a plain SELECT query to consolidate the base data as you wish. 从简单的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;

Then convert to an aggregate ( GROUP BY ) query to compute the sums. 然后转换为聚合查询( 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 #];

I got the impression you may want to store that result set in another table. 我给您的印象是您可能希望将该结果集存储在另一个表中。 However, you may decide that is unnecessary because you can use the query everywhere you would have used another table. 但是,您可能认为这是不必要的,因为您可以在使用另一个表的任何地方使用查询。 However if you do need to store the result set, you can convert to an INSERT query. 但是,如果确实需要存储结果集,则可以转换为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 #];

After you create your table, empty, 创建表格后,请清空,

run the following insert statement: 运行以下插入语句:

 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

另一种方法是在子选择上使用SUM(在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;

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

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