问题
+----+------------+------+
| 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