mySql关于统计数量的SQL查询操作
程序员文章站
2022-03-10 17:44:49
我就废话不多说了,大家还是直接看代码吧~select project_no,sum(case when device_state=0 then 1 else 0 end)as offtotal ,su...
我就废话不多说了,大家还是直接看代码吧~
select project_no, sum(case when device_state=0 then 1 else 0 end)as offtotal , sum(case when device_state=1 then 1 else 0 end)as onlinetotal, sum(1)total from iot_d_device group by project_no order by project_no
补充:mysql一条sql语句查询多条统计结果
商城项目难免会遇到用户个人中心页查询不同状态订单数量的问题。当然这个问题并不难,可以写一个dao层方法,以状态作为入参,每次传入不同状态值依次查询相应状态的订单数量。
今天在写h5端接口时,我想换种方式查,也就是通过一条sql查询出多个状态的订单数量。在网上搜了搜,方法可行,所以就尝试了下,果不其然成功了。
示例如下(数据只为演示今天的问题,表设计并不严谨。勿怪):
set foreign_key_checks=0; -- ---------------------------- -- table structure for mini_test_order -- ---------------------------- drop table if exists `mini_test_order`; create table `mini_test_order` ( `id` int(11) not null, `order_no` varchar(32) default null comment '订单号', `user_id` int(11) default null comment '用户id', `shop_id` int(11) default null comment '商家id', `order_status` tinyint(1) default null comment '订单状态', `create_time` int(10) default null comment '创建时间', primary key (`id`) ) engine=innodb default charset=utf8; -- ---------------------------- -- records of mini_test_order -- ---------------------------- insert into `mini_test_order` values ('1', 'aaaaaaaaa', '11', '111', '1', '1573041313'); insert into `mini_test_order` values ('2', 'bbbbbbbb', '11', '222', '1', '1573041313'); insert into `mini_test_order` values ('3', 'cccccccccc', '11', '333', '2', '1573041313'); insert into `mini_test_order` values ('4', 'dddddddd', '11', '222', '3', '1573041313'); insert into `mini_test_order` values ('5', 'eeeeeeeee', '11', '111', '4', '1573041313'); insert into `mini_test_order` values ('6', 'ffffffffffffff', '11', '111', '3', '1573041313'); insert into `mini_test_order` values ('7', 'gggggggg', '11', '222', '4', '1573041313'); insert into `mini_test_order` values ('8', 'hhhhhhhhh', '11', '111', '4', '1573041313'); insert into `mini_test_order` values ('9', 'iiiiiiiiiiiiiiiiiii', '11', '333', '3', '1573041313'); insert into `mini_test_order` values ('10', 'jjjjjjjjjjjjjjjjjj', '11', '222', '1', '1573041313');
核心sql语句如下:
select count(case order_status when 1 then 1 end) as "状态1",count(case order_status when 2 then 1 end) as "状态2",count(case order_status when 3 then 1 end) as "状态3",count(case order_status when 4 then 1 end) as "状态4" from `mini_test_order`;
或如下:
select count(case when order_status = 1 then 1 end) as "状态1",count(case when order_status = 2 then 1 end) as "状态2",count(case when order_status = 3 then 1 end) as "状态3",count(case when order_status = 4 then 1 end) as "状态4" from `mini_test_order` ;
当然,sql语句不仅仅局限于上述两种写法,喜欢探究的童靴欢迎留言补充。
mysql的case when的语法有两种
1.简单函数
case [col_name] when [value1] then [result1]…else [default] end
2.搜索函数
case when [expr] then [result1]…else [default] end
两者区别
前者枚举col_name这个字段值为符合条件value1时所有可能的值;
后者可以写判断,并且搜索函数只会返回第一个符合条件的值,其他case被忽略。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。