I want to combine information from two data table, t1 and t2
t1:
ID TIME_ADD
1 1620838960308
2 1620879991077
3 1620927396290
t2:
ID TIME_START TIME_END LEVEL
1 1620837000611 1620840600621 0
2 1620837000611 1620846000620 1
3 1620837000611 1620851400622 0
4 1620837000611 1620879262116 3
5 1620837000611 1620881062117 2
6 1620837000611 1620882862117 0
7 1620923400574 1620923400577 2
8 1620923400574 1620930600578 1
...
therefore, I have the query as following:
SELECT t1.*, t2.LEVEL
FROM t1
INNER JOIN t2
ON t2.TIME_START < t1.TIME_ADD AND t2.TIME_END >= t1.TIME_ADD
WHERE t1.TIME_ADD >= '1620837000611' AND t1.TIME_ADD <= '1620882862117'
ORDER BY t1.TIME_ADD
GROUP BY t1.TIME_ADD
And expected result to be
ID TIME_ADD LEVEL
1 1620838960308 0
2 1620879991077 2
However, the query above does not work, and it seems to be that I'm using ORDER BY and GROUP BY wrongly. Spent quite some time to try to find out a way, also looking into using INNER JOIN with LIMIT, but without success. So any support here would be highly appreciated.
The
ORDER BYclause comes after theGROUP BYclause.If you want 1 row for each distinct
TIME_ADDoft1with theLEVELof the row with the minIDoft2, you can do it withHAVING MIN(t2.ID), which is a feature of SQLite (assuming there is noIDint2with a0value):See the demo.