INNER在sql中连接表

时间:2018-05-16 20:39:56

标签: sql-server-2012 inner-join

我有两张桌子,我想加入。

TABLE_A:

+--------+-----------+---------+
| row_id | category  | val_1   |
+--------+-----------+---------+
| 1      | cat1      | 6.5     |
| 1      | test      | 6.5     |
| 1      | dog1      | 2.1     |
+--------+-----------+---------+


TABLE_B:

+-----------+-----------+
| row_id    | val_2     |
+-----------+-----------+
| 1         | 2.0       |
+-----------+-----------+

当我使用INNER JOIN时,得到如下结果:

+-----------+-----------+-----------+------------+
| row_id    | category  | val_1     | val_2      |
+-----------+-----------+-----------+------------+
| 1         | cat1      | 6.5       | 2.0        |
| 1         | test      | 6.5       | 2.0        |
| 1         | dog1      | 2.1       | 2.0        |
+-----------+-----------+-----------+------------+

但我不希望有重复的Val_2结果。我想要这样的结果:

+-----------+-----------+-----------+------------+
| row_id    | category  | val_1     | val_2      |
+-----------+-----------+-----------+------------+
| 1         | cat1      | 6.5       | 2.0        |
| 1         | test      | 6.5       | NULL       |
| 1         | dog1      | 2.1       | NULL       |
+-----------+-----------+-----------+------------+

如果有人可以帮助我,我真的很感激。

1 个答案:

答案 0 :(得分:0)

这会有用吗,迈克?这可能不是您需要的,但您可以根据需要进行调整。

SELECT 
    TABLE_A.*,
    CASE ROW_NUMBER() OVER(PARTITION BY TABLE_B.val_2 ORDER BY TABLE_A.row_id DESC) 
        WHEN 1 THEN TABLE_B.val_2
        ELSE NULL
    END as val_2
FROM
    TABLE_A
INNER JOIN
    TABLE_B ON  TABLE_A.row_id = TABLE_B.row_id
ORDER BY
    TABLE_A.Row_id
祝你好运,迈克!