我是PHP和SQL查询的新手但是正在努力学习。无论如何,我有以下代码,我确信会有一个更简单的方法(希望我打算在一年中的某一天做同样的事情而不仅仅是一个月)。
我目前的代码是;
//Get jan power consumption
$janquery = mysql_query("SELECT SUM(kw*tdsecs) FROM data WHERE year(time) = year(CURDATE()) AND month(time) = 1");
$janresult = mysql_fetch_array($janquery);
$jankwm = $janresult[0] / 60;
$jankwh = round($jankwm / 60,2);
//Get feb power consumption
$febquery = mysql_query("SELECT SUM(kw*tdsecs) FROM data WHERE year(time) = year(CURDATE()) AND month(time) = 2");
$febresult = mysql_fetch_array($febquery);
$febkwm = $febresult[0] / 60;
$febkwh = round($febkwm / 60,2);
依旧......
$values=array(
"Jan" => $jankwh,
"Feb" => $febkwh,
"Mar" => $markwh,
"Apr" => $aprkwh,
"May" => $maykwh,
"Jun" => $junkwh,
"Jul" => $julkwh,
"Aug" => $augkwh,
"Sep" => $sepkwh,
"Oct" => $octkwh,
"Nov" => $novkwh,
"Dec" => $deckwh
);
我希望避免有12个查询,以便获得任何帮助。
答案 0 :(得分:2)
SELECT
month(time) as `month`,
SUM(kw*tdsecs) as `sum`
FROM data
WHERE year(time) = year(CURDATE())
group by month(time)
order by month(time)
答案 1 :(得分:0)
SELECT month(time), SUM(kw*tdsecs) FROM data
WHERE year(time) = year(CURDATE()) group by month(time);
答案 2 :(得分:0)
mysql_query("SELECT month(time),SUM(kw*tdsecs) FROM data WHERE
year(time) = year(CURDATE()) AND month(time) in
(1,2,3,4,5,6,7,8,9,10,11,12) group by month(time)")
答案 3 :(得分:0)
一个简单的解决方案(不是最好的)是循环几个月并将结果存储在一个数组中:
for($month=1; $month<=12; $month++) {
$query = mysql_query(
"SELECT SUM(kw*tdsecs) FROM data
WHERE year(time) = year(CURDATE()) AND month(time) = $month");
$result = mysql_fetch_array($query);
$kwm[$month] = $result[0] / 60;
$kwh[$month] = round($kwm[$month] / 60,2);
}