Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
There are two tables - Table1 and Table2.

Table1 has the following fields

vId, sId
1 1
1 16

Table2 has the following fields

sId, SDate SUnits
1 15-10-2004 1.5
1 14-08-2004 1.20

My query should select the vId, sId, SUnits for the Max(date) for a particular sId in table2. If a sId is not present in Table2, it should still display a row with null values for columns.
Final result that is required is -

vId sId SUnits
1 1 1.5
1 16 Null

I have written the below query. The query does not bring the second row (1,16,null).
It fails to retrieve records from Table2 for which there are no matching rows for sId(16).

SQL
Select Table1.vId,Table1.sId,sUnits
from Table1 Left Join Table2
ON Table1.sId=Table2.sId
where sDate=(
SELECT MAX(sdate) FROM  Table2 AS S
      WHERE S.sId = Table2.sId or sDate is null)
 and vId=1


Any thoughts?
Posted

1 solution

Moved "sDate is null" to outside the bracket and that worked.
SQL
Select Table1.vId,Table1.sId,sUnits
from Table1 Left Join Table2
ON Table1.sId=Table2.sId
where (
sDate=(SELECT MAX(sdate) FROM Table2 AS S
WHERE S.sId = Table2.sId)
OR sDate is null)
and vId=1
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900