MySQL是一款流行的開源關系型數據庫管理系統,它支持按時間和類型進行分組操作,下面我們來詳細看看。
先看一下表結構: CREATE TABLE `orders` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `type` varchar(20) NOT NULL, `time` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 插入一些測試數據: INSERT INTO `orders` (`name`, `type`, `time`) VALUES ('order1', 'type1', '2022-04-01 10:00:00'), ('order2', 'type2', '2022-04-01 11:00:00'), ('order3', 'type1', '2022-04-02 10:00:00'), ('order4', 'type2', '2022-04-02 11:00:00'), ('order5', 'type2', '2022-04-02 12:00:00');
按時間分組
SELECT DATE(time) as date, count(*) as num FROM orders GROUP BY DATE(time); 執行結果: date num 2022-04-01 2 2022-04-02 3
按類型分組
SELECT type, count(*) as num FROM orders GROUP BY type; 執行結果: type num type1 2 type2 3
按時間和類型分組
SELECT type, DATE(time) as date, count(*) as num FROM orders GROUP BY type, DATE(time); 執行結果: type date num type1 2022-04-01 1 type1 2022-04-02 1 type2 2022-04-01 1 type2 2022-04-02 2
上一篇dw外接css