[英]group by column and except one value
表:消息
id is_main message status
-------------------------------
1 0 testt 1
2 5 testt2 1
3 4 testt3 1
4 5 testt4 1
5 0 testt5 1
6 5 testt6 1
7 4 testt7 1
8 5 testt8 1
9 0 testt9 1
我想按is_main分組,但is_main = 0除外
我想要的結果
id is_main message status
-------------------------------
1 0 testt 1
2 5 testt2 1
3 4 testt3 1
3 0 testt5 1
4 0 testt9 1
您可以使用CASE WHEN ... THEN
有條件地進行分組。 首先,您按is_main
列分組,然后必須為不等於0的記錄添加特殊的隨機值列,以將它們從分組中排除。
SELECT *, rand() as rand
FROM messages
GROUP BY is_main, CASE WHEN is_main = 0 THEN rand END;
結果:
+----+---------+---------+--------+---------------------+
| id | is_main | message | status | rand |
+----+---------+---------+--------+---------------------+
| 1 | 0 | testt | 1 | 0.3822869391946932 |
| 9 | 0 | testt9 | 1 | 0.30222991509570735 |
| 5 | 0 | testt5 | 1 | 0.45369350393646724 |
| 3 | 4 | testt3 | 1 | 0.6502720663792193 |
| 2 | 5 | testt2 | 1 | 0.9594265706459307 |
+----+---------+---------+--------+---------------------+
當然,列rand
只是幫助者,為了解決您的問題,它僅在組中使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.