在Mysql中填充总销售额

时间:2014-09-15 12:11:47

标签: mysql sql

我正在开发一个需要复杂报告的应用程序。

 Total Sales

 Product | Quantity Sold |Total Amount
 --------+---------------+------------
 Coke    |           10  |...
 Pepsi   |            2  |...

我的实际mysql表如下。表格名称为“sales”。

+---+----------+-------+------+--------+
|ID |ProductID |Name   |Price |Quantity|
+---+----------+-------+------+--------+
| 1 |        1 |Coke   |   45 |       2|
| 2 |        1 |Coke   |   45 |       1|
| 3 |        3 |Pepsi  |   50 |       1|
| 4 |        1 |Coke   |   50 |       3|
| 5 |        3 |Pepsi  |   50 |       1|
| 6 |        1 |Coke   |   40 |       1|
| 7 |        1 |Coke   |   45 |       3|
+---+----------+-------+------+--------+

我尝试了以下查询但未获得正确的结果。

SELECT DISTINCT Name AS Product, Price, SUM(Quantity) AS Quantity Sold FROM sales GROUP BY Price;

这里同一产品的价格从一行变为另一行。并Name

任何帮助将不胜感激。提前致谢。

2 个答案:

答案 0 :(得分:1)

product中没有group by。并且,在使用select distinct时,您几乎不需要group by。所以,试试这个:

SELECT Name AS Product, SUM(Quantity) AS QuantitySold, SUM(Quantity * Price) as TotalAmount
FROM sales
GROUP BY Name;

答案 1 :(得分:1)

Select Name as Product ,
Sum(quantity) as 'quantity sold',
Sum(quantity*price) as 'total amount'
Group by name;
相关问题