Aggregate
使用 sql 計算表的不同值的計數
name number ============= lin | 8 lin | 8 lin | 8 rob | 8 rob | 8 rob | 8 lin | 8 lin | 41 lin | 41 rob | 41
我想要這樣的結果
name | Count of 8 | count of 41 ==================================== lin | 4 | 2 rob | 3 | 1
任何人都可以幫助我嗎?
這稱為條件計數,可以使用
case
表達式來實現:select name, count(case when number = 8 then 1 end) as count_of_8, count(case when number = 41 then 1 end) as count_of_41 from the_table group by name order by name;
聚合函式(如
count()
)忽略NULL
值。對於我們不想計算的那些值,case
內部的表達式返回null,因此只計算包含該值的行數。相當於count()``case when x then y end``case when x then y else null end
如果使用 PostgreSQL 9.4+,使用新的聚合
filter
子句是最有效的方法:select name, count(*) filter (where number = 8) as count_of_8, count(*) filter (where number = 41) as count_of_41 from <table> group by name;