2017-09-27 11 views
1

私が望む日付/時刻フィールドでMax(SampleDateTime)またはMin()を使用すると、クエリは1の値を返しますが、MaxまたはMinを省略すると値は返されません。私はすべての値を返すが、私はこれを把握することはできない。SQL:日付範囲の選択

すべての品質サンプルは、本番稼動の開始時間と停止時間の間に入れたいです。

RunSamples:

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

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

QualitySamples TBL:
ID SampleDateTime
1 1/1/2017 2 am
2 1/1/2017 3 am
...

ここでは、完全な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])); 
+0

私達にあなたのデータを表示してください。 RunStartDateとRunEndDateの2つの日付の間に実際のデータがありますか? – Joe

+0

あなたはMAXを使用しているので、1つの値しか得られません。 – FLICKER

+0

右 - 私がMAXを削除した場合、クエリから値が得られない – shwan

答えて

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の日付をリストする必要があります。より具体的な要件に基づいて、そこから結果を絞り込むことができます。

+0

ありがとうございました。すべての助けにジョー - 魅力のように動作します。左参入が必要 – shwan

+0

@shwan - 喜んで助けてください。 LEFT JOINとINNER JOINの違いをお読みください。あなたは[ここ](https://en.wikipedia.org/wiki/Join_(SQL))を開始することができます – Joe

0

いけないMAXまたはMINを持っています。 SELECTクエリを持っているだけです。

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

Hmm ...これは「このサブクエリで最大1つのレコードを返すことができる」と言います。 – shwan

+0

@shwan OH ...これは大きなクエリ内のサブクエリであるはずですか? – Joe

+0

右上に全コードを掲載しました – shwan

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] 
+0

ありがとうロバート - キーは内部結合でした! – shwan

関連する問題