简体   繁体   中英

How to join multiple tables by selecting the whole values in the first table and some values in the second table

I have been having problems with my sql query. I am trying to fetch all the values from a user table and sum the loan they have collected this month on the Loan table but I am getting error every time I run the query.

Here is the sql query

SELECT * FROM customer c 
     INNER JOIN(SELECT SUM(loan_amt) as lamt, disb_date, ac_no FROM loans GROUP BY ac_no) AS l ON c.cust_no=l.ac_no

Please, what am I doing wrong? Thanks.

尝试这个:

SELECT c.*,l.lamt FROM customer c INNER JOIN(SELECT SUM(loan_amt) as lamt, disb_date, ac_no FROM loans GROUP BY ac_no,disb_date) AS l ON c.cust_no=l.ac_no

You are selecting more columns in the select than are in the group by . So:

SELECT c.*, l.lamt
FROM customer c LEFT JOIN
     (SELECT SUM(loan_amt) as lamt, ac_no
      FROM loans
      GROUP BY ac_no
     ) l
     ON c.cust_no = l.ac_no;

Note that I also changed the join to LEFT JOIN . Your question specifically says "all rows", and that suggests even rows without loans.

I agree Gordon linoff. It's because your group by doesn't include disb_date even though it's in the select part of the sub-query. However, you don't want to add it in your group by because it probably won't produce the correct results.

I'm guessing you want the disb_date because you want retrieve loans for a particular month. Is this correct? If so, I would add a where clause to Gordon's solution:

SELECT c.*, l.lamt
FROM customer c LEFT JOIN
     (SELECT SUM(loan_amt) as lamt, ac_no
      FROM loans WHERE disb_date BETWEEN <insert date> AND <insert date>
      GROUP BY ac_no
     ) l
     ON c.cust_no = l.ac_no;

This will bring up the sum of the loans which were only collected for your specified month.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM