表数据:

    userid        userType
------------------------------------------
      A               1
      B               1
      B               1
      C               2

需求:查出userType=1和userType=2的用户数,并且直接用字段展示出来,可能还有很多其他类型,也需要同时展示。

去重加上条件查询:

select 
    COUNT(DISTINCT case when userType=1 then userid else null end) as 类型1,
    COUNT(DISTINCT case when userType=2 then userid else null end) as 类型2
from table

解析:distinct会把userid去重统计,如果是null就不会统计,如果是按其他字段去重,可以把userid替换成其他字段名。

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐