views:

87

answers:

1

Hi, I have 2 tables:

  • loans (columns: id, user)
  • payback (columns: id, installment, scheduleDate)

If a loan is to be paid in 12 installments, then there are 12 payback records with loan id.

I would like to find out what users have a scheduleDate on which the sum of all their paybacks is greater than 2000.

SELECT user 
FROM {loans} ka 
WHERE 
(
   SELECT MAX(inst) FROM 
   (
        SELECT SUM(installment) AS inst 
        FROM {payback} 
        WHERE id IN 
        (
            SELECT id 
            FROM {loans} 
            WHERE user = ka.user
        )  
   GROUP BY scheduleDate
   ) as t1 LIMIT 0,1
) > 2000

I'm getting the error: Unknown column 'ka.user' in 'where clause'

A: 

Does this work as requested? It assumes, that payback.id is a foreign key referring to loads.id.

SELECT
  user, scheduleDate, sumInstallments
FROM
(
    SELECT
      l.user, pb.scheduleDate, SUM(pb.installment) AS sumInstallments
    FROM
      payback AS pb
    JOIN
      loans AS l
    ON
      l.id = pb.id
    GROUP BY
      l.user, pb.scheduleDate
) AS tempId
WHERE
  sumInstallments > 2000
Thomas
Yes, payback.id is a foreign key to loans.id. Now I'm getting this error: Unknown column 'sumInstallments' in 'where clause' query
MSto
Meh, I was hoping it'd have the sum available in the WHERE clause already. I'll fix it in a minute.
Thomas
@MSto: Try the edited version. Sorry about the trial and error. I don't have a db available right now to play with, so it's a dry run for me to write up the query. ;)
Thomas
@Thomas, it works. Thanks for your help :)
MSto
@MSto: Glad to help. If you want to show appreciation, accept/vote up my answer. ;)
Thomas
@Thomas, I sure will. BTW I removed pb.id from group by clause, though.
MSto
@MSto: Sure, makes sense. You want to accumulate over all loans of one user, not just a specific one. Nice catch. I've adjusted my answer accordingly.
Thomas
@Thomas, sorry voting up requires 15 reputation ;(
MSto
@MSto: No worries. ;)
Thomas