是否可以在SQL Server中使用SQL-显示表A中的所有记录,即使

时间:2019-04-29 18:10:24

标签: sql-server

我有两个如下表:第一个表存储一个列表并用作主列表

表A

 ImageId    ImageName
 ---------------------
 101        X-Ray
 102        MRI
 103        CTSCAN

我的第二张表显示了上述情况的医院报告:

表B

HospitalId Month  ImageId    NumberOfVisits
-------------------------------------------
111        1      101        20
111        1      102        30
222        1      101        21

现在,我想创建一个如下查询。我想显示表B中表A的全部内容,即使表B中不存在表A的记录

表C

HospitalId Month   ImageName   NumberOfVisits
----------------------------------------------
111        1       X-Ray       20
111        1       MRI         30
111        1       CTSCAN       0
222        1       X-Ray       21
222        1       MRI          0
222        1       CTSCAN       0

我正在尝试创建报告或表格以总结每月医院的服务数量。如果医院一个月没有报告,我想显示0。

我尝试过左连接,但没有帮助。

我尝试了并集查询,但无法正常工作

SELECT        
    B.Hospitalid, A.ImageName, B.Month, B.NumberOfVisits
FROM          
    dbo.TableA A 
INNER JOIN 
    dbo.TableB B ON A.ImageId = B.ImageId

UNION ALL 

SELECT        
    B.Hospitalid, A.ImageName, B.Month, B.NumberOfVisits
FROM          
    dbo.TableA A 
INNER JOIN 
    dbo.TableB B ON A.ImageId = B.ImageId
WHERE
    A.ImageId & B.HospitalId NOT IN (SELECT A.ImageId&B.HospitalId 
                                     FROM dbo.TableA A 
                                     INNER JOIN dbo.TableB B ON A.ImageId = B.ImageId)

即使表B中不存在表A的记录,我也想显示表B中表A的所有内容

HospitalId Month   ImageName   NumberOfVisits
---------------------------------------------
111        1       X-Ray       20
111        1       MRI         30
111        1       CTSCAN       0
222        1       X-Ray       21
222        1       MRI          0
222        1       CTSCAN       0

1 个答案:

答案 0 :(得分:3)

使用交叉联接获取您的图像,医院和月份。然后左联接TableB

with cte as (select     *
             from       (select distinct ImageId, ImageName from tableA) as a1
             cross join (select distinct HospitalId from tableB)         as b1
             cross join (select distinct month from tableB) as b2 )
select      cte.HospitalId
            , cte.Month
            , cte.ImageName
            , coalesce(tb.NumberOfVisits, 0) as NumberOfVisits
from        cte
left join   dbo.TableB as tb on  tb.HospitalId = cte.HospitalId
                             and tb.ImageId = cte.ImageId
                             and tb.Month = cte.Month