![](/img/trans.png)
[英]How to write“greatest n per group” type query, but with additional conditions?
[英]How to write the sql query to select and group by type and count per type?
下面是我的數據庫表。
id name type
1 a 1
2 a 1
3 a 1
4 a 0
5 a 0
6 b 1
7 b 1
8 b 0
9 b 0
10 b 0
11 c 1
12 c 1
13 c 0
我想按類型進行選擇和分組,並按類型進行計數。 如何編寫sql查詢以獲得以下結果?
name count_type_0 count_type_1
a 2 3
b 3 2
c 1 2
只需使用條件聚合:
select name, sum(type = 0) as count_0, sum(type = 1) as count_1
from t
group by name;
它使用MySQL功能,將布爾值視為數字上下文中的數字,其中0表示false,1表示true。 因此,將這些值相加即可計算表達式為真的次數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.