對於報表查詢,就效率來講,通常屬於查詢極慢的SQL語句,同時也是使用頻率極低的語句,因為除了管理員,不會有太多人會去查詢報表;
數據的處理交給Java代碼處理,還是給數據庫處理,並沒有什么好爭論的,直接看問題:
如圖:根據random的值,按照日期統計出每日的優良中差各出現的次數
##建表語句 CREATE TABLE `cj` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `dat` date NOT NULL, `ran` smallint(4) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; INSERT INTO `cj` (`id`, `dat`, `ran`) VALUES ('1', '2017-09-05', '1'); INSERT INTO `cj` (`id`, `dat`, `ran`) VALUES ('2', '2017-09-06', '3'); INSERT INTO `cj` (`id`, `dat`, `ran`) VALUES ('3', '2017-09-05', '3'); INSERT INTO `cj` (`id`, `dat`, `ran`) VALUES ('4', '2017-09-01', '2'); INSERT INTO `cj` (`id`, `dat`, `ran`) VALUES ('5', '2017-09-02', '3'); INSERT INTO `cj` (`id`, `dat`, `ran`) VALUES ('6', '2017-09-03', '4'); INSERT INTO `cj` (`id`, `dat`, `ran`) VALUES ('7', '2017-09-04', '5'); INSERT INTO `cj` (`id`, `dat`, `ran`) VALUES ('8', '2017-09-05', '1'); INSERT INTO `cj` (`id`, `dat`, `ran`) VALUES ('9', '2017-09-01', '3'); INSERT INTO `cj` (`id`, `dat`, `ran`) VALUES ('10', '2017-09-02', '4'); INSERT INTO `cj` (`id`, `dat`, `ran`) VALUES ('11', '2017-09-03', '5'); INSERT INTO `cj` (`id`, `dat`, `ran`) VALUES ('12', '2017-09-04', '1'); INSERT INTO `cj` (`id`, `dat`, `ran`) VALUES ('13', '2017-09-05', '2'); INSERT INTO `cj` (`id`, `dat`, `ran`) VALUES ('14', '2017-09-02', '3'); INSERT INTO `cj` (`id`, `dat`, `ran`) VALUES ('15', '2017-09-02', '3'); INSERT INTO `cj` (`id`, `dat`, `ran`) VALUES ('16', '2017-09-01', '4'); INSERT INTO `cj` (`id`, `dat`, `ran`) VALUES ('17', '2017-09-02', '5'); INSERT INTO `cj` (`id`, `dat`, `ran`) VALUES ('18', '2017-09-03', '1'); INSERT INTO `cj` (`id`, `dat`, `ran`) VALUES ('19', '2017-09-05', '3'); INSERT INTO `cj` (`id`, `dat`, `ran`) VALUES ('20', '2017-09-02', '4'); INSERT INTO `cj` (`id`, `dat`, `ran`) VALUES ('21', '2017-09-04', '5'); INSERT INTO `cj` (`id`, `dat`, `ran`) VALUES ('22', '2017-09-05', '3'); INSERT INTO `cj` (`id`, `dat`, `ran`) VALUES ('23', '2017-09-05', '1'); INSERT INTO `cj` (`id`, `dat`, `ran`) VALUES ('24', '2017-09-05', '2'); INSERT INTO `cj` (`id`, `dat`, `ran`) VALUES ('25', '2017-09-01', '3'); INSERT INTO `cj` (`id`, `dat`, `ran`) VALUES ('26', '2017-09-02', '4'); INSERT INTO `cj` (`id`, `dat`, `ran`) VALUES ('27', '2017-09-05', '3'); ##查詢語句 SELECT A.DAT, max(CASE WHEN A.ran = 1 THEN A.CON ELSE 0 END) '差', max(CASE WHEN A.ran = 2 THEN A.CON ELSE 0 END) '較差', max(CASE WHEN A.ran = 3 THEN A.CON ELSE 0 END) '中', max(CASE WHEN A.ran = 4 THEN A.CON ELSE 0 END) '良', max(CASE WHEN A.ran = 5 THEN A.CON ELSE 0 END) '優' FROM ( SELECT DATE(T.dat) dat,COUNT(1) CON,T.ran FROM cj T WHERE T.dat > DATE(DATE_SUB(NOW(),INTERVAL 30 DAY)) GROUP BY DATE(T.dat),T.ran ) A GROUP BY A.DAT