最近我发现SQLite不支持看似postgresql特定的DISTINCT ON()
子句。例如,如果我的表t
包含列a
和b
。我想选择具有不同b
的所有项目。在SQLite中,以下查询是唯一一种正确的方法吗?
select * from t where b in (select distinct b from t)
示例数据:
a | b
__|__
1 5
2 5
3 6
4 6
我期待的回报:
a | b
__|__
1 5
3 6
答案 0 :(得分:11)
sqlite> SELECT * FROM t GROUP BY b; 2|5 4|6 (for each b: one (unpredictable) value of a) sqlite> SELECT * FROM (SELECT * FROM t ORDER BY a DESC) GROUP BY b; 1|5 3|6 (for each b: the row with min a) sqlite> SELECT * FROM (SELECT * FROM t ORDER BY a ASC) GROUP BY b; 2|5 4|6 (for each b: the row with max a)
答案 1 :(得分:8)
使用:
SELECT MIN(t.a) AS A,
t.b
FROM TABLE t
GROUP BY t.b