列的SUM和显示多个查询

时间:2014-05-07 02:01:26

标签: mysql sql

我有下表:MyTable

enter image description here

我需要显示以下数据: 生产线 buyPrice MSRP

buyPrice和MSRP都需要使用SUM作为数据并通过productLine编制索引,因此输出结果如下:

PRODUCTLINE

飞机
船舶
列车厢式货车和小船

buyPrice
每个productLine的buyPrice中所有值的总和

MSRP
每个productLine的MSRP中所有值的总和

我使用以下查询没有任何成功:

$result = mysql_query("SELECT SUM(buyPrice) FROM myTable, SELECT SUM(MSRP) FROM myTable, SELECT * FROM myTable"); // selecting data through mysql_query()

这是我的条件

while($row = mysql_fetch_array($result))
{
// we are running a while loop to print all the rows in a table
echo "<tr>";  
echo "<td align='center' width='200'>" . $row['productLine'] . "</td>";  
echo "</tr>";  

echo "<tr>";  
echo "<td align='center' width='200'>" . $row['SUM(buyPrice)'] . "</td>";  
echo "</tr>"; 
}  

echo "<tr>";  
echo "<td align='center' width='200'>" . $row['SUM(MSRP)'] . "</td>";  
echo "</tr>"; 
echo "</table>";  

我没有得到任何输出。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

尝试使用:

$result = mysql_query("SELECT productLine, SUM(buyPrice) AS sum_buy_price, SUM(MSRP) AS sum_msrp FROM myTable group by productLine"); // selecting data through mysql_query()

并输出结果:

echo "<table>";
while($row = mysql_fetch_array($result))
{
    // we are running a while loop to print all the rows in a table
    echo "<tr>";  
    echo "<td align='center' width='200'>" . $row['productLine'] . "</td>";  
    echo "<td align='center' width='200'>" . $row['sum_buy_price'] . "</td>";  
    echo "<td align='center' width='200'>" . $row['sum_msrp'] . "</td>";  
    echo "</tr>"; 
}
echo "</table>";