2014-10-30 29 views
0

我有一個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 
+0

你試過了什麼? – Cfreak 2014-10-30 01:41:52

+0

「新用戶總和」是什麼意思?第二週爲什麼是200而不是250? – 2014-10-30 01:43:41

+0

什麼構成新用戶?一個誰以前沒有出現過? – 2014-10-30 01:43:46

回答

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 

UPDATE

基於@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 

希望它有幫助。

+0

它會每週覆蓋多個交易嗎? – skobaljic 2014-10-30 02:07:22

+0

你是什麼意思,你可以詳細說一下,@skobaljic? – 2014-10-30 02:15:16

+0

一位用戶可以在一週內完成更多的交易,這個總和會是多少? – skobaljic 2014-10-30 02:37:58

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

這應該工作。我不認爲你會需要總金額(金額),但嘗試兩種方式。

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是用了一個星期

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