通过连接三个表创建视图

Create a view by joining three tables

我正在尝试加入三个 table。第一个 table 有档案信息,第二个 table 有入院信息,第三个有出院信息。

Table1:会员信息

No, 
Name, 
Sex, 
DBO, 
CaseNo, 
SeqNum,
StartDate,
......

Table 2:授权信息

No,
Name,    
DBO,
CaseNo,
SeqNum,
StartDate,
Admin_1,
Admin_2,
Admin_3,
...

Table3:出院信息

CaseNo,
SeqNum,
DisDate,
DisRea,
...

这是我的查询:

Select    a.no, 
          a.Name, 
          a.Sex, 
          a.DBO, 
          a.CaseNo, 
          a.SeqNum,
          a.StartDate,
          b.Admin_1,
          b.Admin_2,
          b.Admin_3,
          c.DisDate,
          c.DisRea
 from     dbo.mem_information as a inner join dbo.auth_information as b on b.caseno = a.caseno AND 
          b.seqnum = a.seqnum AND        
          b.StartDate = a.StartDate 
          inner join dbo.discharge_information as c ON c.caseno = b.caseno AND
          c.seqnum = b.seqnum 

我的结果示例:

 Name   Sex     DBO     CaseNo  SeqNum  Admin_1  Admin_2 Admin_3 DisDate DisRea
  Jones   M    19980615    23      1       SING
  Jones   M    19980615    23      1               LAUGH
  Smith   F    19960212    24      1       SING

期望的结果:

 Name  Sex     DBO     CaseNo  SeqNum  Admin_1  Admin_2 Admin_3 DisDate DisRea
 Jones   M    19980615    23      1     SING     LAUGH            
 Smith   F    19960212    24      1     SING

可能还没有任何出院数据,但我希望这些字段显示为 NULL。

在Null字段旁边有解决办法如果没有出院数据那么可能就没有条目了。你应该使用左连接来组合 table 'discharge_information'。 sql 查询如:

Select    a.no, 
          a.Name, 
          a.Sex, 
          a.DBO, 
          a.CaseNo, 
          a.SeqNum,
          a.StartDate,
          b.Admin_1,
          b.Admin_2,
          b.Admin_3,
          c.DisDate,
          c.DisRea
 from     dbo.mem_information as a inner join dbo.auth_information as b on b.caseno = a.caseno AND 
          b.seqnum = a.seqnum AND        
          b.StartDate = a.StartDate 
          left join dbo.discharge_information as c ON c.caseno = b.caseno AND
          c.seqnum = b.seqnum;

在此处查看联接的用法 LEFT JOIN vs. LEFT OUTER JOIN in SQL Server

由于您没有提供任何示例数据,所以不确定如何测试它,但我假设您正在寻找这样的东西:

CREATE VIEW dbo.VIEW_NAME AS
SELECT a.[no]
    ,a.NAME
    ,a.Sex
    ,a.DBO
    ,a.CaseNo
    ,a.SeqNum
    ,MIN(a.StartDate) StartDate
    ,MAX(b.Admin_1) Admin_1
    ,MAX(b.Admin_2) Admin_2
    ,MAX(b.Admin_3) Admin_3
    ,MAX(c.DisDate) DisDate
    ,MAX(c.DisRea) DisRea
FROM dbo.mem_information AS a
INNER JOIN dbo.auth_information AS b ON b.caseno = a.caseno
    AND b.seqnum = a.seqnum
    AND b.StartDate = a.StartDate
LEFT JOIN dbo.discharge_information AS c ON c.caseno = b.caseno
    AND c.seqnum = b.seqnum
GROUP BY  a.[no]
    ,a.NAME
    ,a.Sex
    ,a.DBO
    ,a.CaseNo
    ,a.SeqNum;