消除JOIN列中记录的重复项

时间:2018-10-22 15:14:54

标签: sql sql-server sql-server-2017

初始数据示例:

  Table 1                                             Table 2
|  ID   |   Name   |  Cost   |  Cost2  |           |  ID   |   Info1   |   Info2   |
|-------|----------|---------|---------|           |-------|-----------|-----------|
|  1    |   Name1  |   20    |   50    |           |  1    |   text1   |   text1   |
|  2    |   Name2  |   30    |   10    |           |  1    |   text1   |   text1   |
|  2    |   Name22 |   30    |   40    |           |  1    |   text1   |   text1   |
|  3    |   Name3  |   20    |   50    |           |  2    |   text21  |   text21  |
|  4    |   Name4  |   30    |   70    |           |  2    |   text22  |   text22  |
                                                   |  2    |   text23  |   text23  |
                                                   |  2    |   text24  |   text24  |

在我的初始数据中,我通过字段 ID 在2个表之间建立了关联。我需要将第二个表加入第一个表。 所以这是Leftjoin = table1.ID的{​​{1}}的简单结果

table2.ID

| ID | Name | Cost | Cost2 | Info1 | Info2 | |-------|----------|---------|---------|-----------|-----------| | 1 | Name1 | 20 | 50 | text1 | text1 | | 1 | Name1 | 20 | 50 | text1 | text1 | | 1 | Name1 | 20 | 50 | text1 | text1 | | 2 | Name2 | 30 | 10 | text21 | text21 | | 2 | Name2 | 30 | 10 | text22 | text22 | | 2 | Name2 | 30 | 10 | text23 | text23 | | 2 | Name2 | 30 | 10 | text24 | text24 | | 2 | Name22 | 60 | 40 | text21 | text21 | | 2 | Name22 | 60 | 40 | text22 | text22 | | 2 | Name22 | 60 | 40 | text23 | text23 | | 2 | Name22 | 60 | 40 | text24 | text24 | 在字段(成本,成本2)上如何不进行复制而获得结果

预期结果:

join

2 个答案:

答案 0 :(得分:1)

join需要一个“行号”。您的表没有一个,但是您可以使用row_number()添加一个:

select coalesce(t1.id, t2.id) as id,
       t1.name, t1.cost, t2.info1, t2.info2
       . . .
from (select t1.*, row_number() over (partition by id order by (select null)) as seqnum
      from table1 t1
     ) full join
     (select t2.*, row_number() over (partition by id order by (select null)) as seqnum
      from table2 t2
     ) t2
     on t1.id = t2.id and t1.seqnum = t2.seqnum;

a,您不会使用此方法获得name。但这是有道理的。它仅在table1中,因此不应该在每个匹配的行上。

编辑:

那不是完全正确。您希望重复行。然后值不出现。我认为这是条件逻辑:

如果您确实需要它:

select t1.id, t1.name,
       (case when row_number() over (partition by t1.id order by (select null)) = 1 then cost END) as Cost,
       t2.info1, t2.info2
from table1 t1 join
     table2 t2
     on t1.id = t2.id ;

答案 1 :(得分:1)

您可以尝试使用row_number窗口函数在子查询中创建行号,然后通过Cost获取Cost2CASE WHEN,行号为1 < / p>

SELECT ID,
    Name,
    CASE WHEN rn = 1 THEN Cost end, 
    CASE WHEN rn = 1 THEN Cost2 end,  
    Info1,
    Info2      
FROM (
    SELECT  
       t1.ID,
       Name,
       Cost,
       Cost2,
       Info1,
       Info2,   
       row_number() over(partition by Name order by Info1) rn
    FROM Table1 t1 JOIN table2 t2 on t1.id = t2.id
) t1

sqlfiddle