MySQL总和只有新行

时间:2014-10-30 01:38:40

标签: mysql

我有一个这种格式的MySQL表

transaction |  user   | amount | week
------------|---------|--------|------
     1      | user_1  |  100   |  1
     2      | user_2  |   50   |  1
     3      | user_1  |   50   |  2
     4      | user_3  |  200   |  2

我知道如何计算MySQL中每周的总金额,但MySQL有没有办法计算每周新用户的金额?

因此,对于这个表,它将是:

week 1 = 150
week 2 = 200

4 个答案:

答案 0 :(得分:1)

是的,有。您可以使用MIN(week)的值来指示特定用户的第一笔交易。

SELECT w, SUM(amount)
FROM(
    SELECT user, amount, MIN(week) AS w
    FROM `trans`
    GROUP BY user) newUserTrans
GROUP BY w

如果您仍想显示没有新用户的一周,那么您可以使用:

SELECT week, IFNULL(SUM(amount),0) AS total
FROM(
    SELECT user, amount, MIN(week) AS w
    FROM `trans`
    GROUP BY user) newUserTrans RIGHT JOIN (SELECT DISTINCT week FROM trans) weeks ON newUserTrans.w = weeks.week
GROUP BY w
ORDER BY week

<强>更新

基于@skobaljic意见,我还提供了另一种替代方案,用户可能在同一周内有多个记录。

SELECT weeks.week AS Week, IFNULL(SUM(amount),0) AS Total
FROM(
    SELECT trans.user, trans.amount, trans.week
    FROM trans
      JOIN (SELECT user, MIN(week) AS w
              FROM trans
              GROUP BY user) newWeek ON trans.user = newWeek.user
           AND trans.week = newWeek.w) newUserTrans
    RIGHT JOIN (SELECT DISTINCT week FROM trans) weeks ON newUserTrans.week = weeks.week
GROUP BY newUserTrans.week
ORDER BY weeks.week

希望它有所帮助。

答案 1 :(得分:0)

我希望这可能会有所帮助:

select sum(A.`amount`) from `table` AS A WHERE A.`user` NOT IN (SELECT B.`user` FROM `table` AS B where A.`week` > B.`week') AND A.`week` = @pWeek

其中@pWeek是具有特定周数的参数

答案 2 :(得分:0)

我认为有更好的方式让用户获得第一周。

第一周是用户的最短周。

select
    trans.week
   ,sum(amount) as amount
from trans
inner join
    (select 
        user
       ,min(week) as firstweek
    from 
        trans
    group by
        user
    ) as firstweek
on  trans.user = firstweek.user
where
    trans.week = firstweek.firstweek
group by 
    trans.week

答案 3 :(得分:-1)

$query = "SELECT * FROM [table] GROUP BY week";

这应该有效。我不认为你需要总和(金额),但要尝试两种方式。