SQL一次性获取总和和所有行

时间:2017-11-13 14:38:59

标签: mysql

我试图同时获得列数和所有行的总和。

SELECT sum(orders.amount) as total, orders.transactionID, orders.itemid, products.id, 
products.category, products.price 
FROM db.orders 
INNER JOIN db.products 
ON orders.itemid = products.id 
WHERE transactionID = '012906ea51c14b0881c4785527c606dd'

上面的查询只给出了总值,只有一行(我也希望拥有所有行)

SELECT sum(orders.amount) as total, orders.transactionID, orders.itemid, products.id, 
products.category, products.price 
FROM db.orders 
INNER JOIN db.products 
ON orders.itemid = products.id 
WHERE transactionID = '012906ea51c14b0881c4785527c606dd'
GROUP BY orders.id

虽然第二个查询为我提供了每一行,但总共orders.amount

不正确

可以这样做吗?

(我将两个查询缩短了一点)

由于

1 个答案:

答案 0 :(得分:2)

您可以使用"运行总计",这意味着,使用变量并自己汇总值。正确的总和将出现在结果集的最后一行。

SELECT @my_sum := @my_sum + orders.amount as running_total, 
orders.transactionID, 
orders.itemid, 
products.id, 
products.category, 
products.price 
FROM db.orders 
INNER JOIN db.products 
ON orders.itemid = products.id 
CROSS JOIN (SELECT @my_sum:=0) AS var_init_subquery
WHERE transactionID = '012906ea51c14b0881c4785527c606dd'
  • 详细了解用户变量here

另请参阅Raymond Nijland的评论:

  

查询1 ..没有GROUP BY的SUM总是生成1行。查询2是GROUP BY读取https://www.psce.com/en/blog/2012/05/15/mysql-mistakes-do-you-use-group-by-correctly/

的无效使用