DISTINCT clause in SQLite

吃可爱长大的小学妹 提交于 2020-01-21 03:16:27

问题


Recently i found that SQLite don't support DISTINCT ON() clause that seems postgresql-specific. For exeample, if i have table t with columns a and b. And i want to select all items with distinct b. Is the following query the only one and correct way to do so in SQLite?

select * from t where b in (select distinct b from t)

Sample data:

a | b
__|__
1   5
2   5
3   6
4   6

What i expect in return:

a | b
__|__
1   5
3   6

回答1:


Use:

  SELECT MIN(t.a) AS A,
         t.b
    FROM TABLE t
GROUP BY t.b



回答2:


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)


来源:https://stackoverflow.com/questions/3038575/distinct-clause-in-sqlite

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!