我有一个包含多列的表格:
table1 | column1 | column2 | column3 |
| x | .... | .... |
| y | .... | .... |
| x | .... | .... |
如何统计一个值(例如x)在一列中(例如column1)出现的次数?针对table1,这将返回2(column1中存在x的数量)。
我有一个包含多列的表格:
table1 | column1 | column2 | column3 |
| x | .... | .... |
| y | .... | .... |
| x | .... | .... |
如何统计一个值(例如x)在一列中(例如column1)出现的次数?针对table1,这将返回2(column1中存在x的数量)。
您可以使用带有CASE
语句的SUM()
聚合函数,例如:
select sum(case when column1 = 'x' then 1 else 0 end) as X_Count
from tabl1;
sum
的优点是,您可以在一个select
中计算多个总和,而count
则计算select
的所有结果。 - cevingcount(*)
相比,另一个优点是您将获得明确的 0,用于未满足所有条件的组,而不是将该组从结果中省略。例如,select gcol, count(*) from tbl where wcol = 'foo' group by gcol
不会有任何行,其中 wcol
不是 'foo',而 select sum(case when wcol = 'foo' then 1 else 0 end) from tbl group by gcol
将为所有不同的 gcol
值提供一行。可能很明显...但我最终来到这里,因为我想要 0,而 count
没有给我。 - pyansharpSELECT COUNT(*) FROM table1 WHERE column1 = 'x'