Parent Child table record - Building SQL query [duplicate]

倖福魔咒の 提交于 2019-12-12 04:57:36

问题


Possible Duplicate:
Parent Child table record - Building SQL query

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:


@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



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/2091409/parent-child-table-record-building-sql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!