是特定數量的參數,有。您可以使用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
希望它有幫助。
你試過了什麼? – Cfreak 2014-10-30 01:41:52
「新用戶總和」是什麼意思?第二週爲什麼是200而不是250? – 2014-10-30 01:43:41
什麼構成新用戶?一個誰以前沒有出現過? – 2014-10-30 01:43:46