vendredi 20 mars 2015

how to check conditions in one table and return a value from another table?

I wrote this if statement:


if( client.loancycle = 0 AND activationdate > date_sub(curdate(), interval 1 month), loanaccount.loanamount, 0 )


The big question is: When the conditions evaluate to TRUE, will this return the record from loanaccount.loanamount that corresponds to this record in client.loancycle?


If this isn't giving the right value from the other table, how do I make the if statement return the right value from the other table?


The if statement comes form this query:


Select format(sum(if(Client.Loancycle = 0 AND Activationdate > date_sub(curdate(), interval 1 month), Loanaccount.Loanamount, 0)), "Currency") as "Total Loaned This Month (NEW)-Amt", count(if(Client.Loancycle = 0 AND Activationdate > date_sub(curdate(), interval 1 month), Loanaccount.Encodedkey, NULL)) as "Total Loaned This Month (NEW)-Num" FROM Client, Loanaccount WHERE ACCOUNTSTATE<>"CLOSED" ;


The query is working, but it comes out to 0. I know not every client has a loan, so I wonder if it's getting the right records.


E.g. This month I have 3 new clients and 1 took out a loan. The loan was for $200. This is what I want the result to look like:



Total Loaned This Month (NEW)-Amt | Total Loaned This Month (NEW)-Num
200 | 1


I want to check the conditions about when the client, but return values from the loan table that correspond to that client.


Encodedkey is the primary key in every table.


Accountholderkey is the foreign key in Loanaccount that connects to Client.


I'm trying to make an sql fiddle here, but I can't figure out how to make loanaccount.accountholderkey a foreign key.


I've tried reading these questions too, but I couldn't find what I need.


Select values from one table depending on referenced value in another table


MySQL returning results from one table based on data in another table


How to check if a column value is refered in some other table as that colum is a foreign key in other table (sql server)?


Insert new record in table depending upon conditions in another


Aucun commentaire:

Enregistrer un commentaire