mySql關於統計數量的SQL查詢操作

我就廢話不多說瞭,大傢還是直接看代碼吧~

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被忽略。

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。如有錯誤或未考慮完全的地方,望不吝賜教。

推薦閱讀: