我就废话不多说了,大家还是直接看代码吧~
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被忽略。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。