I need to SELECT all rows (*) in my table between rows with records (TIME = 08.38 AND LINE = 28) AND (TIME = 10.20 AND LINE = 28) only if these two rows has the same GROUP_ID (selected rows must have the same GROUP_ID of these two rows).
db_table example with 4 rows:
ID TIME LINE GROUP_ID
__________________________________________
A) 1 08.32 28 5
B) 2 09.18 28 5
C) 3 10.20 28 5
D) 4 10.25 28 6
In my example the query must return row B) because ordering rows by ID it is between row A) with records (TIME = 08.32 AND LINE = 28) and row C) with records (TIME = 10.20 AND LINE = 28) and it has the same GROUP_ID = 5.
Anyone can help me?
Try below :
select * form db_table
where TIME between '08.38' AND '10.20' and LINE = 28
group by GROUP_ID
You could also try self join , like :
Select * from TestTable T1
Inner Join TestTable T2 On T1.GroupID=T2.GroupID
Where (T1.Time > '08:38:00.0000000' And T1.Time < '10:20:00.0000000') AND
(T2.Time > '08:38:00.0000000' And T2.Time< '10:20:00.0000000') AND
T1.Line=28 And T2.Line=28
I am not sure I fully follow what you are after but based on what I think you are after this should work:
SELECT t.*
FROM db_table t1
INNER JOIN
( SELECT Group_ID, Line, MIN(Time) [MinTime], MAX(Time) [MaxTime]
FROM db_table
GROUP BY Group_ID, Line
) t2
ON t2.Group_ID = t1.Group_ID
AND t2.Line = t1.Line
WHERE t1.Time > t2.MinTime
AND t2.Time < t2.MaxTime
I think this canbe performed more efficiently with joins, but since i am not even sure this yields the right results I will hold fire on optimising it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.