mysql count distinct如何加条件?比如有数据表swimTable:
name swimLocation
张三 A
李四 A
李四 B
张三 A
我想统计游泳馆A有多少人过去?不能使用where,想使用如下语句,但是报错了:
select count(if(swimLocation='A'),distinct name,false) from swimTable;
select sum(distinct name) from swimTable group by swimLocation having swimLocation='A'
select count(distinct name) from swimTable group by swimLocation having swimLocation='A'不好意思上面写错函数了,试一下这个行不
select swimLocation,count(distinct name) from swimTable group by swimLocation
select swimLocation,count(1) from swimTable group by swimLocation
这样会得到 如下数据
A 3
B 1
你循环下数据就可以拿到你想要的数据
可以使用count(distinct case where 条件 then 字段 end),具体参见:https://stackoverflow.com/questions/19672001/mysql-distinct-count-if-conditions-unique