我有一列QualityCheckTimes。我还有一个与ProductionSkids的StartTimes和EndTimes不同的表。
我需要一个针对每个QualityCheckTime返回的查询,最小SkidID和基于StartTimes和EndTimes的最大SkidID。
示例数据
QCCheckTimes
12:00 AM
1:00 AM
2:00 AM
SkidID SkidStartTime SkidEndTime
1 12:05 AM 12:20 AM
2 12:21 AM 12:40 AM
3 12:41 AM 12:50 AM
4 12:51 AM 1:06 AM
预期输出:
QCCheckTimes MinSkidID MaxSkidID
12:00 AM Skid1 Skid3
1:00 AM Skid4 ...
2:00 AM ...
我尝试了一些方法,但问题的关键在于我需要找到一种方法来在两个QualityCheck时间之间获得所有匹配的滑动时间,这些QualityTimes位于不同的行上。
SELECT...
WHERE [SkidStartDateTime] >= [QualitySamples_tbl].[SampleDateTime]
AND [SkidEndDateTime] < NEXT?? [QualitySamples_tbl].[SampleDateTime]);
答案 0 :(得分:0)
您可以使用子查询和Hour()
函数来实现此目的。
试试这个:
table1 包含:QCCheckTimes
table2 包含:SkidID,SkidStartTime,SkidEndTime
代码:
SELECT table1.qcchecktimes,
Iif([minofid] IS NULL, "...", "skid" & [minofid]) AS MinSkidID,
Iif([c].[maxofid] = [b].[minofid], "...",
Iif([maxofid] IS NULL, "...", "skid" & [maxofid])) AS MaxSkidID
FROM (table1
LEFT JOIN (SELECT table1.qcchecktimes,
Min(table2.skidid) AS MinOfID
FROM table1,
table2
WHERE (( ( Hour([skidendtime]) ) = Hour([qcchecktimes]) ))
GROUP BY table1.qcchecktimes) AS b
ON table1.qcchecktimes = b.qcchecktimes)
LEFT JOIN (SELECT table1.qcchecktimes,
Max(table2.skidid) AS MaxOfid
FROM table1,
table2
WHERE (( ( Hour([skidendtime]) ) = Hour([qcchecktimes]) ))
GROUP BY table1.qcchecktimes) AS c
ON table1.qcchecktimes = c.qcchecktimes
GROUP BY table1.qcchecktimes,
Iif([minofid] IS NULL, "...", "skid" & [minofid]),
Iif([c].[maxofid] = [b].[minofid], "...",
Iif([maxofid] IS NULL, "...", "skid" & [maxofid]));
答案 1 :(得分:0)
我不使用访问权限但是在SQL Server中你有两个函数来实现这个查询 LAG 和 LEAD ,上一行和下一行,你可以在这里看到一个教程http://www.c-sharpcorner.com/UploadFile/f82e9a/lag-and-lead-functions-in-sql-server/
所以在SQL中你可以做这样的事情(这个例子是使用整数而不是时间)
----------------your single table-----------------
declare @a table(id int)
insert into @a
select 1 union
select 5 union
select 10 union
select 14 union
select 17 union
select 20
----------------table with ranges-----------------
declare @b table (start int, finish int)
insert into @b
select 1,4 union
select 2,5 union
select 5,8 union
select 10,15
----------------Aux Table--------------------------
declare @a_PlusNext table (id int, idNext int)
insert into @a_PlusNext
SELECT id,LEAD(id) OVER(ORDER BY id) nextId from @A
----------------------Final Query------------------
SELECT
*
FROM @a_PlusNext
INNER JOIN @b on start >= id and finish <= idNext