Say I have the following schema:
create table client (clientid int) create table mv (clientid int, fundid int, date datetime, value decimal) insert into client values(1) insert into mv values(1, 1, '1 may 2010', 35) insert into mv values (1,1, '1 may 2011', 434) insert into mv values (1, 2, '1 may 2011', 635) The first table represents the client, and the second table represents their market value and the fund they are invested in.
I need to display their market value per fund at 2 dates, but display 0 for a date if I cant find a record for that date.
Here is my attempt:
select c.clientid, mvstart.fundid startfundid, mvend.fundid endfundid, mvstart.value startvalue, mvend.value endvalue from client c left join mv mvstart on c.clientid = mvstart.clientid and mvstart.date = '1 may 2010' left join mv mvend on c.clientid = mvend.clientid and mvend.date = '1 may 2011' Which produces:
CLIENTID STARTFUNDID ENDFUNDID STARTVALUE ENDVALUE 1 1 1 35 434 1 1 2 35 635 I don't understand why the second row has a startvalue of 35.
I need to have the following output:
CLIENTID FUNDID STARTVALUE ENDVALUE 1 1 35 434 1 2 0 635 Can anyone help me join correctly or explain why my query produces 35 as the startvalue for the 2nd row?
Heres a SQLFiddle
on c.clientid = mvstart.clientid and mvstart.date = '1 may 2010'. It only get the value35twice, that's why you see35twice there.