2013-03-07 53 views
0

在下面的表格中,我将如何为特定年份的价格总和(比如2013)编写select子句?像SUM(价格WHEN年= 2012)。我将如何参考PHP mysql_fetch_array()中的结果。在PHPPHP MySQL仅在某些条目中使用SELECT获得SUM

SELECT SUM(price) AS my_sum 
WHERE year = 2102 

然后:

+++++++++++++++++++++++++++++ 

Price | Date | Month | Year | 

+++++++++++++++++++++++++++++ 

9.00 |343345| 2 | 2013 | 

3.00 |343445| 2 | 2013 | 

4.00 |343245| 1 | 2013 | 

1.00 |342245| 1 | 2013 | 

5.00 |333355| 12 | 2012 | 
+0

确实有总你真的把日期分成多列? 5分钟我在SELECT的手册页面可能会回答这个基础知识。 – 2013-03-07 01:34:53

回答

1

使用别名

$row = mysqli_fetch_assoc($result); 
echo $row['my_sum']; 
+1

'SUM(price WHEN year = 2012)' - 除非我错了,那不是一个有效的表达式 – 2013-03-07 01:46:34

1

select sum(price) from table where year = 2012;

你会提到它通过使用:

$data = mysql_fetch_array($query); 
echo $data[0]; 
1

造成这种情况的查询将是下面一个:

select sum(price) as total_price from your_table_name where Year='2012'; 

而在PHP中,你可以使用它作为:

$getTotal = mysql_query("select sum(price) as total_price from your_table_name where Year='2012'"); 
while($resTotal = mysql_fetch_array($getTotal)) 
{ 
$total = $resTotal['total_price']; 
} 

现在你在变量$总

+0

[**请不要在新代码中使用'mysql_ *'函数**](http:// bit .ly/phpmsql)。他们不再被维护[并被正式弃用](https://wiki.php.net/rfc/mysql_deprecation)。看到[**红框**](http://j.mp/Te9zIL)?学习[*准备的语句*](http://j.mp/T9hLWi),并使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/ mysqli) - [这篇文章](http://j.mp/QEx8IB)将帮助你决定哪个。如果你选择PDO,[这里是一个很好的教程](http://j.mp/PoWehJ)。 – 2013-03-07 01:52:26

+0

^^^^尽可能真实,它对于常规的S.O用户每天看到它10次以上有点乏味 – 2013-03-07 01:54:11