Sqlite GROUP BY priority

大兔子大兔子 提交于 2021-01-28 05:29:07

问题


+----+------------+------+
| id |   title    | lang |
+----+------------+------+
|  1 | title 1 EN | en   |
|  1 | title 1 FR | fr   |
|  1 | title 1 ZH | zh   |
|  2 | title 2 EN | en   |
|  3 | title 3 ZH | zh   |
+----+------------+------+

this is my table and I want to group by id but I sometimes I need language "en" to have priority and sometimes I need to have language "zh" as priority

SELECT * FROM table GROUP BY id

gives me a list of all uniqe ids but places zh in favor for id 1, is it possible that I can add a priority for language?

My desired output for "en":

+----+------------+------+
| id |   title    | lang |
+----+------------+------+
|  1 | title 1 EN | en   |
|  2 | title 2 EN | en   |
|  3 | title 3 ZH | zh   |
+----+------------+------+

My desired output for "fr":

+----+------------+------+
| id |   title    | lang |
+----+------------+------+
|  1 | title 1 FR | fr   |
|  2 | title 2 EN | en   |
|  3 | title 3 ZH | zh   |
+----+------------+------+

my desired .. on and on :)


回答1:


Since SQLite 3.7.11, you can select which record in a group is returned by using MAX or MIN. A boolean expression like lang = 'en' returns either 0 or 1:

SELECT *,
       MAX(lang = 'en')
FROM MyTable
GROUP BY id

If you want to have priorities for more than one language, you can use a CASE expression:

SELECT *,
       MAX(CASE lang
           WHEN 'en' THEN 2
           WHEN 'fr' THEN 1
                     ELSE 0
           END)
FROM MyTable
GROUP BY id


来源:https://stackoverflow.com/questions/18943934/sqlite-group-by-priority

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