使用默认值插入两个表的select查询

时间:2014-11-30 18:54:36

标签: sql-server vb.net sql-server-2008 tsql sql-insert

表1:INVOICE (CNum, PatID, RefBy)

CNum  |PatID  | RefBy
=======================
101   |201    | Dr.Ram
102   |202    | Dr.John
104   |201    | Dr.Philander
104   |203    | Dr.Smith
105   |204    | Dr.Bashir
106   |201    | Dr.Raj

表2:PATIENT (PatID, Name)

PatID  | Name
======================
201    | Jay
202    | Robert
203    | Divya
204    | Sarala
205    | Pratheeksha
206    | Tim

表3 BASECASE(CaseNumber, Name, CaseTopic, RefBy, TrtDoctor)

SQL查询

Insert into BASECAS
  from CHECKUP and PATIENT
  (CaseNumber from PatientID of PATIENT /* all the rows */)
  (Name from Name of PATIENT /*All the rows corresponding to PatientID */)
  (CaseTopic column will have `-` for all rows)
  (MAX(RefBy) from RefBy CHECKUP where PATIENT.PatientID = CHECKUP.PatientID, If the Patient.PatientID does not exist in **Table1 - CHECKUP**, it should return **'-'**)
  (TrtDoctor column will have '-' for all rows)

查询后的预期结果:

CaseNumber | Name       | CaseTopic | RefBy    | TrtDoctor
==========================================================
201        | Jay        | -         | Dr.Ram   | -
202        | Robert     | -         | -        | -
203        | Divya      | -         | Dr.Smith | -
204        | Sarala     | -         | Dr.Bashir| -
205        | Pratheeksha| -         | -        | -
206        | Tim        | -         | -        | -

如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

认为你可以这样做:

INSERT INTO BASECASE
SELECT pat.PatID, pat.Name, '-', COALESCE(ref.RefBy, '-'), '-' 
FROM PATIENT pat
LEFT JOIN 
(
   SELECT PatID, MAX(RefBy) RefBy FROM INVOICE GROUP BY PatID
) ref ON ref.PatID = pat.PatID

答案 1 :(得分:0)

您的样本输出数据似乎与描述不符:CaseNumber中的数字似乎是PatID,而不是CNum,而且患者Robert应该有一个RefBy Dr.John我认为?< / p>

表1的表名首先作为INVOICE给出,然后称为CHECKUP,我假设后者是正确的。

请确保您的说明和示例数据/输出正确

在任何情况下,要获得样本输出,这应该有效:

INSERT BASECASE (CaseNumber, Name, CaseTopic, RefBy, TrtDoctor)
SELECT 
    CaseNumber = p.PatID, 
    p.Name,
    CaseTopic = '-',
    RefBy = ISNULL(RefBy,'-'),
    TrtDoctor = '-'
from PATIENT p 
OUTER APPLY (
             SELECT MAX(RefBy) AS RefBy 
             FROM CHECKUP 
             WHERE p.PatID = PatID
            ) Ref