1. 程式人生 > >mysql語句 一個表統計每天產生的不同型別資料 根據型別欄位 統計每天有多少

mysql語句 一個表統計每天產生的不同型別資料 根據型別欄位 統計每天有多少


DROP TABLE IF EXISTS `risk_business02`;
CREATE TABLE `risk_business02` (
  `rb02id` bigint(20) NOT NULL COMMENT '主鍵',
  `rb01id` bigint(20) DEFAULT NULL COMMENT '風險商戶1主鍵',
  `settleDate` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '日期',
  `createTime` datetime DEFAULT NULL COMMENT '產生日期',
  `b01id` bigint(20) DEFAULT NULL COMMENT '商戶ID',
  `reason` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '風險原因(0:夜間交易頻繁  1:交易地點分散  2:交易金額固定)',
  `fxpc` int(11) DEFAULT NULL COMMENT '風險批次',
  PRIMARY KEY (`rb02id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


-- ----------------------------
-- Records of risk_business02
-- ----------------------------
INSERT INTO `risk_business02` VALUES ('1', '1', '2017-05-23', '2017-05-24 18:06:10', '1000000108', '1', '0');
INSERT INTO `risk_business02` VALUES ('2', '2', '2017-05-23', '2017-05-24 18:06:11', '1000000109', '0', '0');
INSERT INTO `risk_business02` VALUES ('3', '1', '2017-05-23', '2017-05-24 18:06:11', '1000000108', '0', '0');
INSERT INTO `risk_business02` VALUES ('4', '1', '2017-05-23', '2017-05-24 18:06:10', '1000000108', '2', '0');
INSERT INTO `risk_business02` VALUES ('5', '2', '2017-05-24', '2017-05-24 18:06:11', '1000000109', '2', '0');
INSERT INTO `risk_business02` VALUES ('6', '1', '2017-05-24', '2017-05-24 18:06:11', '1000000108', '1', '0');


先GROUP BY
settleDate,
reason  欄位 查出 統計每天 分類原因 個數

然後再GROUP BY
settleDate 一次 再sum 分類原因欄位

SELECT
settleDate,
sum(ifnull(r0, 0)) AS r0,
sum(ifnull(r1, 0)) AS r1,
sum(ifnull(r2, 0)) AS r2
FROM
(
SELECT
settleDate,
CASE reason
WHEN 0 THEN
count(reason)
END r0,
CASE reason
WHEN 1 THEN
COUNT(reason)
END r1,
CASE reason
WHEN 2 THEN
COUNT(reason)
END r2
FROM
risk_business02
GROUP BY
settleDate,
reason
)   AS  table_a


WHERE
settleDate >= "2017-05-23"
AND settleDate <= "2017-05-25"
GROUP BY
settleDate
ORDER BY
settleDate DESC
LIMIT 0,
 10