2009-12-12 54 views
0

我有兩個表,一個存儲用戶收入,另一個存儲用戶付款。我想要做的是根據50美元的最低限額並僅從最後一次付款中獲得到期的付款。子查詢以獲取到期付款

表(userEarnings)具有以下列

id ->autoincrement 
userid -> unique id for users 
earn ->the amount of money the user earn (25.00, 14.50..) 
date_added -> DATETIME column 

每個用戶得到支付

pid->autoincrement 
uid ->unique user id, this is the same as userid from the above table 
paid_amt->payments the user received(500.00, 100.00...) 
paid_date ->the date the user was paid(DATETIME) 

來自這兩個表的時間第二個表(userPayment)專賣店,我想列出用戶名和自上次付款以來欠款總和大於50美元的總和。我假設我需要使用子查詢和組,但不知道從哪裏開始。

任何幫助將不勝感激。由於

回答

0

稍微不同的方式,使用not exists子查詢。取決於口味,可以表現不同,並且可以更易於閱讀。

SELECT ue.userid User 
,   SUM(ue.earn) AmountDue 
FROM  userEarnings ue 
WHERE  NOT EXISTS (
      SELECT * 
      FROM userPayment up 
      WHERE up.uid = ue.userid 
      AND up.paid_date >= ue.date_added 
     ) 
GROUP BY ue.userid 
HAVING AmountDue > 50.0 
1

試試這個:

SELECT userEarnings.userid, SUM(earn) AS total_earn FROM (
    SELECT uid, MAX(paid_date) AS paid_date 
    FROM userPayment 
    GROUP BY uid) AS T1 
RIGHT JOIN userEarnings ON T1.uid = userEarnings.userid 
WHERE date_added > T1.paid_date OR T1.paid_date IS NULL 
GROUP BY userEarnings.userid 
HAVING total_earn > 50 
+0

不應該是'有和(賺)> 50'嗎? – 2009-12-12 23:58:56

+0

看起來像SergeyKazachenko是正確的,並且'inner join'過濾了之前從未付款的用戶 – Andomar 2009-12-13 00:20:10

+0

修復了連接到外連接的問題。而且我認爲無論您使用SUM(獲得)還是別名,HAVING都不重要。他們都工作。 – 2009-12-13 00:31:03

1
SELECT userEarnings.userid, SUM(userEarnings.earn) AS earn 
FROM userEarnings 
LEFT OUTER JOIN (
    SELECT uid, MAX(paid_date) AS last_payment 
    FROM userPayment 
    GROUP BY uid) AS q 
ON q.uid = userEarnings.userid 
--the q.last_payment IS NULL clause ensures that the user who never got a payment before will get his first $50 check 
WHERE (userEarnings.date_added > q.last_payment) OR (q.last_payment IS NULL) 
GROUP BY userEarnings.userid 
HAVING SUM(userEarnings.earn) >= 50.0 
+0

+1我認爲這可行 – Andomar 2009-12-13 00:18:59