Mysql统计一张表中不同属性值的数量

现有一张表,此表为设备表,pid为设备的父级设备id,分别统计各设备有多少个子级设备。

第一种解决方法是一条一条输出:

select pid as id,count(*) as totalcount from project_equipments_type_grouping where pid=1;
select pid as id,count(*) as totalcount from project_equipments_type_grouping where pid=2;
select pid as id,count(*) as totalcount from project_equipments_type_grouping where pid=3;

即通过where语句分别统计不同属性的数量。

但显然这样写并不方便,能不能通过一条语句搞定了?

我又写了第二种解法:

 select
 sum(pid = 1) as 'id=1',
 sum(pid = 2) as 'id=2',
 sum(pid = 3) as 'id=3'
 from  project_equipments_type_grouping;

上面这种写法基本能满足我们的要求了,但本着闲着也是闲着的好学态度,又写了第三种解法:

 select pid as id ,count(*) as totalcount from  project_equipments_type_grouping group by pid;

上述解法仅供参考,上面的别名和分组方式只是为了方便本人结果展示。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值