如何合并两个连接查询

时间:2017-01-05 18:07:59

标签: sql-server join merge

我需要在每个部门显示所有工作人员,医生和病人。

我已经尝试过这个查询,没有显示员工,医生,而且工作正常

ALTER view vwDisplay
AS
    select 
        dpt.Department_ID, dpt.Department_Name,
        num_of_doc, num_of_staff, No_of_Patient
    from 
        Department dpt
    join 
        (select 
             count(*) as num_of_doc, Department_ID 
         from 
             Doctor_Main 
         group by 
             Department_ID) dct on dpt.Department_ID = dct.Department_ID
    join 
        (select 
             count(*) as num_of_staff, Department_ID 
         from 
             Other_Staff 
         group by
             Department_ID) stf on stf.Department_ID = dpt.Department_ID

我还需要在每个部门都不显示患者。但是部门和患者之间没有任何关系,医生只适用于一个部门..

此查询我过去常常没有为每位医生显示患者

select count(*) as No_of_Patient, Doctor_Main.Doctor_ID
from Patients_Main
inner join Doctor_Main on Patients_Main.Doctor_ID = Doctor_Main.Doctor_ID
group by Doctor_Main.Doctor_ID

现在我需要合并这两个,当我按如下方式执行此查询时

ALTER view vwDisplay
as
select dpt.Department_ID,dpt.Department_Name,num_of_doc,num_of_staff,No_of_Patient
from Department dpt
    join (select count(*) as num_of_doc,Department_ID from Doctor_Main GROUP  BY Department_ID) dct
    on dpt.Department_ID = dct.Department_ID

    join (select count(*) as num_of_staff,Department_ID from Other_Staff GROUP  BY Department_ID) stf
    on stf.Department_ID = dpt.Department_ID

    --join (select count(*) as No_of_Patient,Doctor_ID from Patients_Main GROUP  BY Doctor_ID) dcth
    --on dcth.Doctor_ID = Doctor_Main.Doctor_ID


    select count(*) as No_of_Patient,Doctor_Main.Doctor_ID
    from Patients_Main
    inner join Doctor_Main on Patients_Main.Doctor_ID = Doctor_Main.Doctor_ID
    group by Doctor_Main.Doctor_ID

发生此错误:

  

关键字附近的语法不正确'选择'。

我可以为这个问题做些什么?或者你还有其他解决办法吗?

1 个答案:

答案 0 :(得分:0)

我想你可以尝试一下。

ALTER view vwDisplay
as
select dpt.Department_ID,dpt.Department_Name,num_of_doc,num_of_staff,No_of_Patient
from Department dpt
    join (select count(*) as num_of_doc,Department_ID from Doctor_Main GROUP  BY Department_ID) dct
    on dpt.Department_ID = dct.Department_ID

    join (select count(*) as num_of_staff,Department_ID from Other_Staff GROUP  BY Department_ID) stf
    on stf.Department_ID = dpt.Department_ID

    join (select count(*) as No_of_Patient,DM.Department_ID from Patients_Main PM
          join Doctors_Main DM ON PM.Doctor_ID = DM.Doctor_ID GROUP  BY DM.Department_ID) dcth
    on dcth.Department_ID = dpt.Department_ID