views:

202

answers:

3

Here is my table and data of these tables

Table name: Code

CID     Code
1       abc
2       def     
3       xyz

Table Name : Details

ID  Date        Value1  CID
1   1/1/2009    12      1       
2   1/1/2009    25      2
3   1/1/2009    18      3
4   1/2/2009    36      1
5   1/2/2009    45      2
6   1/3/2009    19      1

Resultant Table:

Date        Value1  CID     Code
1/1/2009    12      1       abc
1/1/2009    25      2       def
1/1/2009    18      3       xyz
1/2/2009    36      1       abc
1/2/2009    45      2       def
1/2/2009    Null    3       xyz
1/3/2009    19      1       abc
1/3/2009    NUll    2       def
1/3/2009    Null    3       xyz

I need to get all record from the code table and against each code I have to get all the rows from the details table, if some code have value their need value and if not then Null

Thanks

+1  A: 

You need a LEFT JOIN between the Code table and the Details table, as indicated by the possibility of missing data in the result. The final query is left as an exercise, because this looks exactly like an exercise.

Duncan
@Mohammad Looks like your professor found you.
AaronLS
no, its not working...
Muhammad Akhtar
+2  A: 
SELECT  t.* , d.value1
FROM (SELECT * FROM ((SELECT DISTINCT date FROM details) t CROSS JOIN code )) t 
      LEFT JOIN details d ON t.cid = d.cid and t.date = d.date
ORDER BY date, cid
THEn
Thanks, its working fine.
Muhammad Akhtar
+2  A: 

@Muhammad Akhtar, Have a look at this. Let me know if it helps

DECLARE @Code TABLE(
        CID INT,
        Code VARCHAR(10)
)

INSERT INTO @Code SELECT 1,'abc' 
INSERT INTO @Code SELECT 2,'def'      
INSERT INTO @Code SELECT 3,'xyz'

DECLARE @Details TABLE(
        ID  INT,
        Date DATETIME,
        Value1 INT,
        CID INT
)

INSERT INTO @Details SELECT 1,'1/1/2009',12,1        
INSERT INTO @Details SELECT 2,'1/1/2009',25,2 
INSERT INTO @Details SELECT 3,'1/1/2009',18,3 
INSERT INTO @Details SELECT 4,'1/2/2009',36,1 
INSERT INTO @Details SELECT 5,'1/2/2009',45,2 
INSERT INTO @Details SELECT 6,'1/3/2009',19,1 

SELECT  v.Date,
        d.Value1,
        v.CID,
        v.Code
FROM    (
            SELECT  DISTINCT
                    d.Date,
                    c.CID,
                    c.Code
            FROM    @Details d, @Code c
        ) v LEFT JOIN 
        @Details d  ON  v.CID = d.CID 
                    AND v.Date = d.Date
astander
I will not be able to check right now, that is my personal email. Will reply when i get it a little later.
astander