mysql查詢資料時,按照時間分組求和
阿新 • • 發佈:2019-01-31
1、查詢時,同一時間點有多條資料
SELECT date_format(ctime, '%Y-%m-%d %H:%i:%s') ctime, mode_num as mode_num, nose_num_real as nose_num_real, t2.num as num , capacity, limitPower FROM rpps_prod_minute_theory t1 LEFT JOIN rpps_data_power t2 ON t1.ctime = t2.ptime AND t1.group_id = t2.group_id WHERE ctime >='2017-10-10' AND ctime <'2017-10-11' AND t1.farm_id ='1ff499730a72412ebd174b77b31327e1' ORDER BY ttime
2、此處用到了group by 分組函式,根據時間分組。和求和函式sum ,再對每一項求和
SELECT date_format(ctime, '%Y-%m-%d %H:%i:%s') ctime, sum(mode_num) AS mode_num, sum(nose_num_real) AS nose_num_real, sum(t2.num) AS num, capacity, (sum(limitPower) > 0) AS limitPower FROM rpps_prod_minute_theory t1 LEFT JOIN rpps_data_power t2 ON t1.ctime = t2.ptime AND t1.group_id = t2.group_id WHERE ctime >='2017-10-10' AND ctime <'2017-10-11' AND t1.farm_id ='1ff499730a72412ebd174b77b31327e1' GROUP BY ttime ORDER BY ttime
3、(sum(limitPower) > 0) AS limitPower 此處對查詢出來的陣列做個大小判斷,若比較成立則返回1,若不成立則返回0