1

我是 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 个查询,所以任何帮助将不胜感激。

4

4 回答 4

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)
于 2012-09-27T17:12:58.583 回答
0
SELECT month(time), SUM(kw*tdsecs) FROM data 
WHERE year(time) = year(CURDATE()) group by month(time);
于 2012-09-27T17:12:15.103 回答
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)")
于 2012-09-27T17:13:04.943 回答
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);
}
于 2012-09-27T17:14:44.400 回答