SQL:在日期范围之间选择

时间:2017-09-27 20:15:49

标签: sql ms-access

如果我在所需的日期/时间字段上使用Max(SampleDateTime)或Min(),我的查询返回1值,但如果我省略Max或Min,则不返回任何值。我想要返回所有值,但我似乎无法弄清楚这一点。

我希望生产运行的开始和停止时间之间的所有质量样本。

RunSamples:

Select Max([SampleDateTime]) 
FROM [QualitySamples] AS [GoodSamples] 
WHERE [GoodSamples].[SampleDateTime] >= [ProductionRuns_tbl].[RunStartDate] 
    AND [GoodSamples].[SampleDateTime] <= [ProductionRuns_tbl].[RunEndDate]

ProductionRuns_tbl:
RunStartDate RunEndDate
1/1/2017 12 AM 1/5/17 12 AM
...

QualitySamples Tbl:
    ID SampleDateTime
    1 1/1/2017 2上午     2 1/1/2017 3上午 ...

这是完整的SQL代码:

SELECT ProductionRuns_tbl.RunName, ProductionRuns_tbl.RunStartDate, 
ProductionRuns_tbl.RunEndDate,
 (Select Max([SampleDateTime]) 
 FROM [QualitySamples] AS [GoodSamples] 
 WHERE [GoodSamples].[SampleDateTime] >= [ProductionRuns_tbl].[RunStartDate] 
 AND [GoodSamples].[SampleDateTime] <= [ProductionRuns_tbl].[RunEndDate])
AS RunSamples
FROM ProductionRuns_tbl
WHERE (((ProductionRuns_tbl.RunName)=[Forms]![Home]![RunName]));

3 个答案:

答案 0 :(得分:1)

尝试使用连接:

SELECT ProductionRuns_tbl.RunName,
       ProductionRuns_tbl.RunStartDate, 
       ProductionRuns_tbl.RunEndDate,
        GoodSamples.SampleDateTime
FROM QualitySamples GoodSamples INNER JOIN ProductionRuns_tbl ON 
    GoodSamples.SampleDateTime >= ProductionRuns_tbl.RunStartDate AND 
    GoodSamples.SampleDateTime <= ProductionRuns_tbl.RunEndDate
WHERE ProductionRuns_tbl.RunName=[Forms]![Home]![RunName]

答案 1 :(得分:0)

不要 WHERE MAX MIN 。只需要 SELECT 查询。

Select [SampleDateTime]
FROM [QualitySamples] AS [GoodSamples] 

答案 2 :(得分:0)

我现在正在冒险发布,因为我必须尝试阅读你想要做的事情(另外,我不知道这是否适用于Access ,但它将在SQL服务器中工作)

由于您需要所有数据,这是您正在寻找的内容吗?

SELECT 
    ProductionRuns_tbl.RunName, 
    ProductionRuns_tbl.RunStartDate, 
    ProductionRuns_tbl.RunEndDate,
    [QualitySamples].[SampleDateTime]
FROM
    ProductionRuns_tbl
LEFT JOIN
    [QualitySamples]
ON
    [QualitySamples].[SampleDateTime] >= [ProductionRuns_tbl].[RunStartDate] 
    AND
    [QualitySamples].[SampleDateTime] <= [ProductionRuns_tbl].[RunEndDate]
WHERE 
    (((ProductionRuns_tbl.RunName)=[Forms]![Home]![RunName]));

这应列出为每个SampleDateTime重复的RunName,Start和End日期。根据您的更具体要求,您可以从那里优化结果。