sql server - Selecting correlated records from database -
i've been improving sql knowledge still failed understand how create queries.
i have following tables in sql server database:
user(id, name)
loan(id_sender, id_receiver, amount, date, date_payment)
what valid query to:
- select name of users have sent loans user both in 2014 , 2015
- select pairs (id1, id2) of users have sent loans each other
any suggestions appreciated!
edit 1:
my attempts:
1.
select name user id in ( select id_sender loan id_receiver in (select distinct id_receiver year(date) = 2014) , id_receiver in (select distinct id_receiver year(date) = 2015) )
2.
select id1, id2 ( select distinct id_sender id1 loan id_receiver in ( select distinct id_sender loan id_receiver = ??? ) (?) )
example 1: in case date
column has index, it's best not use function around column can utilize index.
select name user id in (select id_sender loan date >= '1/1/2014' , date < '1/1/2015') , id in (select id_sender loan date >= '1/1/2015' , date < '1/1/2016')
example 2: can use self join find matches using loan table.
select l1.id_sender id1, l1.id_receiver id2 loan l1 inner join loan l2 on l1.id_sender = l2.id_receiver , l2.id_sender = l1.id_receiver
Comments
Post a Comment