父子表记录 - 构建SQL查询

时间:2010-01-19 05:50:35

标签: asp.net sql-server-2005 sql

  

可能重复:
  Parent Child table record - Building SQL query

这是我的表格和这些表格的数据

表名:代码

CID     Code
1       abc
2       def     
3       xyz

表名:详情

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

结果表:

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

我需要从代码表中获取所有记录,并且我必须从详细信息表中获取所有行的每个代码,如果某些代码具有其需要值的值,如果没有那么Null

由于

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

@Muhammad Akhtar,看看这个。如果有帮助请告诉我

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 :(得分:1)

Code表和Details表之间需要LEFT JOIN,结果中可能缺少数据。最后的查询留作练习,因为这看起来就像练习一样。