I was trying to retrieve value from two tables by joining, but few values in the second columns missing.
eg
valuetable
----------------------
| id |orderid| prodid|
----------------------
| 1 | NULL | 4|
----------------------
| 1 | A | 4|
----------------------
| 2 | NULL | 4|
----------------------
| 2 | NULL | 3|
----------------------
| 3 | B | 4|
----------------------
| 3 | B | 3|
----------------------
| 3 | B | 5|
----------------------
Nametable
--------------
| id | Name|
--------------
| 1 | Apple|
--------------
| 2 | Ball|
--------------
| 3 | Cat|
--------------
| 4 | Dog|
--------------
I have the above two table. I have to retrieve values in the below format.
Query Result
----------------------
| id | Name|orderid|
----------------------
| 1 | Apple| NULL |
----------------------
| 2 | Ball| NULL |
----------------------
| 3 | Cat| B |
----------------------
| 4 | Dog| NULL |
----------------------
I have used the following query
SELECT nt.id, nt.[Name]
, MIN(vt.orderid) AS orderid
FROM Nametable nt LEFT OUTER JOIN valuetable vt
ON nt.id = vt.id
WHERE
vt.prodid = 3
GROUP BY
nt.id, nt.[Name]
but missing the | 1 | Apple| NULL | row. How can I retrieve it?
using MSSQL Server 2005
UPDATE
value table doesn’t have id value 1 for prodid=3 but I need a result in the above mentioned way. means if it cannot get id from the valuetable for the corresponding prodid it should still retrieve the id and its name with NULL value as orderid.
Seems you have
valuetable does not contain an Apple with prodid = 3
So you should not have in the where but in the join clause: