如何获得上一年的总和与下一年的总和

时间:2014-09-22 12:17:01

标签: php mysql

我有以下查询

SELECT COUNT( DISTINCT id ) AS `total` , YEAR( created_date ) AS `memberYear`
FROM `users` AS `u`
WHERE (
role_id =2
AND is_deleted =0
AND is_trashed =0
)
GROUP BY `memberYear` 

通过这个查询,我得到了这样的记录

total   memberYear
 10        2012 
 12        2013 
 2         2014

现在我需要记录上一年的总和

total   memberYear sumTotal
10        2012       10
12        2013       22
2         2014       24

我怎样才能获得总和的总和?任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:1)

如果您使用存储过程或使用嵌套选择,则只能使用mysql执行此操作,但我不建议使用它。由于您使用PHP并且已经有查询响应,只需将当前年份值添加到上一个:

$sumTotal=0;
while ($row=mysql_fetch_array($res)){
    $sumTotal+=$row["total"];
}

答案 1 :(得分:1)

请试试这个:

SELECT COUNT( DISTINCT id ) AS `total` , YEAR( created_date ) AS `memberYear`,
@running_total := @running_total + COUNT(DISTINCT id) AS total
FROM `users` AS `u`
, (SELECT @running_total := 0) var_init_subquery
WHERE (
role_id =2
AND is_deleted =0
AND is_trashed =0
)
GROUP BY `memberYear` 

答案 2 :(得分:0)

您正在寻找累计金额。不幸的是,mysql还不支持窗口函数,这使得这些事情变得非常容易。一种方法是使用theta self join,如:

SELECT X.memberYear, sum(y.total)
FROM (
    SELECT COUNT( DISTINCT id ) AS `total` , YEAR( created_date ) AS `memberYear`
    FROM `users` AS u
    WHERE role_id =2
      AND is_deleted =0
      AND is_trashed =0
    GROUP BY memberYear
) AS x 
JOIN (
    SELECT COUNT( DISTINCT id ) AS `total` , YEAR( created_date ) AS `memberYear`
    FROM `users` AS `u`
    WHERE role_id =2
      AND is_deleted =0
      AND is_trashed =0
    GROUP BY `memberYear`
) y
   on y.memberyear <= x.memberyear
group by X.memberYear

这是未经测试的,因此可能存在一些错误。