Mysql查询从表中获取总和

时间:2013-08-13 06:08:02

标签: mysql

我想执行数学运算以及从表中获取记录。

示例:我的表格包含以下数据

| orderid | value | orderdate    |
 ----------------------------------
  1       | 100   |  2013-08-08  | 
  2       | 200   |  2013-08-05  | 
  3       | 300   |  2013-08-06  | 
  4       | 400   |  2013-08-09  | 

我期待总和(值)以及从表中获取所有记录。示例输出

sum(value)| orderid | value | orderdate    |
 -------------------------------------------
  1000    | 1       | 100   |  2013-08-08  | 
  1000    | 2       | 200   |  2013-08-05  | 
  1000    | 3       | 300   |  2013-08-06  | 
  1000    | 4       | 400   |  2013-08-09  | 

2 个答案:

答案 0 :(得分:3)

您可以使用CROSS JOIN

SELECT  b.TotalValue, a.*
FROM    tableName a
        CROSS JOIN 
        (SELECT SUM(value) totalValue FROM tableName) b

或相关子查询,

SELECT  (SELECT SUM(value) FROM tableName) totalValue, 
        a.*
FROM    tableName a

答案 1 :(得分:0)

试试这个

SELECT a.*,SUM(b.value) FROM tablename AS a,tablename AS b GROUP BY a.orderid