Mysql Query SUM将每个结果添加到另外的结果中?

时间:2014-04-19 22:26:35

标签: php mysql

很抱歉,如果我的问题毫无意义。不确定我们是否只能使用mysql执行此操作。假设我有这个问题:

SELECT SUM(win) * 100 as win_profit, date, uid FROM `tips` WHERE uid = 60 AND placed = 1 GROUP by date

这显然会得到每天在数据库中的胜利列的总和。

让我们说数据库有:

|___win___|____date____|
|   10    | 2014-04-16 |
|   10    | 2014-04-16 |
|   10    | 2014-04-17 |
|   10    | 2014-04-18 |
|   10    | 2014-04-18 |
|   10    | 2014-04-18 |
|   10    | 2014-04-19 |
|   10    | 2014-04-19 |
|   10    | 2014-04-19 |

这将导致:

20
10
30
30

我怎样才能得到结果所以每个加起来,只有mysql查询。结果将是:

20
30
60
90

2 个答案:

答案 0 :(得分:2)

您可以获取所有不同的日期,并LEFT JOIN查找截至该日期的所有值的总和;我保留了样本查询中的100乘数,但您需要将其删除以获得与所需结果匹配的结果。

SELECT 100 * SUM(b.win), a.date 
FROM (SELECT DISTINCT date FROM `tips`) a
LEFT JOIN tips b ON a.date >= b.date
GROUP BY a.date
ORDER BY a.date

An SQLfiddle to test with

答案 1 :(得分:0)

这可能是另一种方式......

SET @full_sum=0;
SELECT @full_sum+SUM(win) as win_profit, date as this_date, uid, 
@full_sum:=(SELECT @full_sum+SUM(win) 
            FROM `testing` WHERE uid = 60 
            GROUP by date HAVING date=this_date) 
FROM `testing` WHERE uid = 60 GROUP by date;