2009-12-12 51 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