比较每个表中具有多个相同记录的2个表之间的数据

时间:2017-05-02 20:26:05

标签: sql-server

接下来的情况......我没有表之间的唯一标识符来进行匹配,所以我匹配的值可以在两个表中出现多次。我觉得我必须分配一些值,然后在下一条记录试图匹配时删除可用于匹配的记录。

表1包含以下数据:

MedicationName  ID    Pt   Price  SEQ
Drug1           123   AAA  100.00  1
Drug2           345   AAA  200.00  2

Table 2 
InjectionName   ID    PT   StarDate  EndDate
Drug1           123   AAA  20170101  20991231
Drug1           123   AAA  20160417  NULL
Drug2           345   AAA  20161101  20191231

结果应该是这样的:

Medication   MedID   Price  Injection  InjID StartDate  EndDate  PT   Seq
Drug1        123     100.00  Drug1     123   20170101  20991231  AAA   1
*NULL         NULL    NULL    Drug1     123   20160417  NULL      AAA   NULL*
Drug2        345     200.00  Drug2     345   20161101  20191231  AAA   2

但我的结果是:

Medication   MedID   Price  Injection  InjID StartDate  EndDate  PT   Seq
Drug1        123     100.00  Drug1     123   20170101  20991231  AAA   1
*Drug1        123     100.00  Drug1     123   20160417  NULL      AAA   1*
Drug2        345     200.00  Drug2     345   20161101  20191231  AAA   2

我需要表明第2个表中的第2个项目在表1中没有匹配值,因为项目1已经与之匹配。

1 个答案:

答案 0 :(得分:0)

你需要ROW_NUMBER来分隔行..试试这个:

With Table1 As
(
          Select 'Drug1' MedicationName , 123 ID ,'AAA' Pt ,100.00 Price,1 SEQ
    Union Select 'Drug2' MedicationName , 345 ID ,'AAA' Pt ,100.00 Price,1 SEQ
),
Table2 As
(
          Select 'Drug1' InjectionName, 123 ID, 'AAA' PT, 20170101 StarDate, 20991231 EndDate
    Union Select 'Drug1' InjectionName, 123, 'AAA', 20160417, NULL
    Union Select 'Drug2' InjectionName, 345, 'AAA', 20161101, 20191231
),
Table1_Id As
(
    Select 
        Cast (Row_Number() Over (Partition By MedicationName, ID Order BY MedicationName, Id) as Int) MedicationNumber,
        MedicationName, Id, PT, Price, Seq
    From Table1
),
Table2_Id As
(
    Select 
        Cast (Row_Number() Over (Partition By InjectionName, ID Order BY InjectionName, Id) as Int) InjectionNumber,
        InjectionName, Id, PT, StarDate, EndDate
    From Table2
)
Select *
From Table1_Id T1
Full Outer Join Table2_Id T2
    On T1.MedicationName = T2.InjectionName
    And T1.ID = T2.ID
    And T1.MedicationNumber = T2.InjectionNumber