SQLite 中如何在 group by 之前使用 order by?

How to use order by before group by in SQLite?

我想合并来自两个数据 table、t1t2

的信息

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
 ...

因此,我有如下查询:

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

预期结果为

ID TIME_ADD      LEVEL
 1 1620838960308 0
 2 1620879991077 2

但是,上面的查询不起作用,而且我似乎错误地使用了 ORDER BYGROUP BY。花了很多时间试图找到一种方法,也研究了使用 INNER JOINLIMIT,但没有成功。因此,我们将不胜感激任何支持。

ORDER BY 子句在 GROUP BY 子句之后。

如果您想要 t1 中每个不同的 TIME_ADD 和最小 IDt2 的行的 LEVEL 一行,您可以用 HAVING MIN(t2.ID) 来实现,这是 SQLite 的一个特性(假设 t2 中没有 ID 且值为 0):

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'
GROUP BY t1.TIME_ADD
HAVING MIN(t2.ID)
ORDER BY t1.TIME_ADD;

参见demo