[英]PHP and MYSQL Query for sum multiple column
i want to display data from database with calculate sum and mean from each row, it's look like this : 我想显示数据库中的数据,并计算每一行的总和和均值,如下所示:
but, for now, i only can display from year until dec column, and i've done with the basic query like this : 但是,目前,我只能显示从年到dec的列,并且我已经完成了如下基本查询:
rainfall.php rainfall.php
<?php
$servername = "xxxxx";
$username = "xxxx";
$password = "xxxx";
$dbname = "xxxxx";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM rainfall";
$result = $conn->query($sql);
if ($result->num_rows >0) {
// output data of each row
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "0 results";
}
echo $json;
$conn->close();
?>
my rainfall table structure : 我的降雨表结构:
CREATE TABLE IF NOT EXISTS `rainfall` (
`rf_id` int(11) NOT NULL AUTO_INCREMENT,
`estate_id` int(11) NOT NULL,
`year_rainfall` varchar(4) COLLATE utf8_unicode_ci DEFAULT NULL,
`jan` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`feb` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`mar` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`apr` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`may` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`jun` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`jul` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`aug` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`sep` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`oct` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`nov` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`dec` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`rf_id`)
) ;
What should i add into the php code to showing the calculate (sum and mean) like image above ?? 我应该在php代码中添加什么以显示上面图像的计算(总和和均值)? Need your advice ... 需要您的建议...
Replace your SQL query with this one: 用以下内容替换您的SQL查询:
SELECT `Year`,
jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, `dec`,
jan + feb + mar + apr + may + jun + jul + aug + sep + oct + nov + `dec` AS total
FROM rainfall
UNION ALL
SELECT 'Mean',
avg(jan), avg(feb), avg(mar), avg(apr), avg(may), avg(jun),
avg(jul), avg(aug), avg(sep), avg(oct), avg(nov), avg(`dec`),
avg(jan) + avg(feb) + avg(mar) + avg(apr) + avg(may) + avg(jun) +
avg(jul) + avg(aug) + avg(sep) + avg(oct) + avg(nov) + avg(`dec`)
FROM rainfall
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.