嗨,我想我有一张这样的桌子:
________________________________________________________
|
| id | order | date | item | price|
-------------------------------------------------------
| 1 1st date i1 10,00|
|-------------------------------------------------------
| 2 2nd date u2 15,00|
|-------------------------------------------------------
| 3 1st date i1 20,00|
|-------------------------------------------------------
| 4 2nd date u2 30,00|
|-------------------------------------------------------
我需要获得包含相同订单名称的项目的总和,并打印DISTINCT订单,如:
order_name - 日期 - 总和。或更好的方法来创建新的表格并存储每个订单的总和,并在此表中添加每行的总和ID?
答案 0 :(得分:1)
使用GROUP BY
:
SELECT SUM(`price`)
FROM `orders`
GROUP BY `order`
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html
答案 1 :(得分:1)
假设您的order_name - date - total sum
列为date
date
SELECT CONCAT(order, " - ", date, " - ", SUM(price)) as Result
FROM orders
GROUP BY `order`
要添加数量,请尝试以下操作:
SELECT CONCAT(order, " - ", date, " - ", CASE WHEN quantity > 1 THEN (quantity * SUM(price)) ELSE SUM(price) END) as Result
FROM orders
GROUP BY `order`