我正在尝试在 PostgreSQL 9.0 中构建一个查询,该查询获取特定列的最长连续行序列。
考虑下表:
lap_id (serial), lap_no (int), car_type (enum), race_id (int FK)
Run Code Online (Sandbox Code Playgroud)
lap_no每个(race_id, car_type). where都是独一无二的。
我希望查询为给定的race_idand生成最长的序列car_type,因此它将返回int最高的(或长的)。
使用以下数据:
1, 1, red, 1
2, 2, red, 1
3, 3, red, 1
4, 4, red, 1
5, 1, blue, 1
6, 5, red, 1
7, 2, blue, 1
8, 1, green, 1
Run Code Online (Sandbox Code Playgroud)
对于car_type = red and race_id = 1查询将5作为lap_no字段的最长序列返回。
(我也想知道car_type …
我有一个 Postgres 数据库表foo,其中有一个score范围为 0 - 10的列。我想要一个查询来返回分数总数、0 到 3 之间的分数数、4 之间的分数数和 6,以及 7 到 10 之间的分数。类似于以下内容:
SELECT
COUNT(*) as total,
COUNT(
SELECT * from foo where score between 0 and 3;
) as low,
COUNT(
SELECT * from foo where score between 4 and 6;
) as mid,
COUNT(
SELECT * from foo where score between 7 and 10;
) as high
FROM foo;
Run Code Online (Sandbox Code Playgroud)
我试过这个,但SELECT在COUNT语句中出现错误。任何想法我怎么能做到这一点?我确定 Postgres 中有一个超级简单的方法。我只是想不出 Google 的正确术语。