如何在不重复ID的情况下构建视图?

时间:2018-07-10 14:41:57

标签: sql sql-server join view

我想将三个表连接在一起,并创建一个视图作为查找。问题是我得到了重复的provider id,因为provider_name是不同的。

表1

provider_id  provider_name
545          Kent Hospital

表2

provider_id  provider_name
565          Devin Hospital

表3

provider_id  provider_name
545          Kent Medical Center

我得到了:

provider_id  provider_name
545          Kent Hospital
545          Kent Medical Center
565          Devin Hospital

最终预期结果:

provider_id  provider_name
545          Kent Hospital
565          Devin Hospital

实际上,使用哪个名称都没有关系,因为它们通常几乎相同。

但是问题是我在provider_id中得到重复,这导致我对其他表的联接出现重复记录。我知道可以使用this之类的方法来避免在连接到端点表时出现这种情况,但是在我看来,这似乎是一种绷带,而不是核心解决方案。

我目前的做法:

--CREATE VIEW lookup_providers AS 
SELECT DISTINCT provider_id, provider_name
FROM table1
UNION
SELECT DISTINCT provider_id, provider_name
FROM table2
UNION
SELECT DISTINCT provider_id, provider_name
FROM table3

样本表

CREATE TABLE table1 (provider_id nvarchar(30), provider_name nvarchar(30))
CREATE TABLE table2 (provider_id nvarchar(30), provider_name nvarchar(30))
CREATE TABLE table3 (provider_id nvarchar(30), provider_name nvarchar(30))

INSERT INTO table1 (provider_id, provider_name) VALUES ('545','Kent Hospital')
INSERT INTO table2 (provider_id, provider_name) VALUES ('565','Devin Hospital')
INSERT INTO table3 (provider_id, provider_name) VALUES ('545','Kent Medical Center')

2 个答案:

答案 0 :(得分:2)

如果您不关心名称,请使用GROUP BY

SELECT provider_id, MIN(provider_name) as provier_name
FROM ((SELECT provider_id, provider_name
       FROM table1
      ) UNION ALL
      (SELECT provider_id, provider_name
       FROM table2
      ) UNION ALL
      (SELECT provider_id, provider_name
       FROM table3
      )
     ) tt
GROUP BY provider_id;

如果要选择一个特定的名称,则有更多精心设计的机制-最长,最短的表优先级。但是,您可以指定任意名称为好,因此MIN()应该做您想做的事。

答案 1 :(得分:1)

一个小小的猜测,但我认为您正在追求类似的东西:

CREATE VIEW lookup_providers AS

    WITH CTE AS(
        SELECT provider_id, provider_name
        FROM table1
        UNION
        SELECT provider_id, provider_name
        FROM table2
        UNION
        SELECT provider_id, provider_name
        FROM table3),
    RNs AS(
        SELECT provider_id, provider_name,
               ROW_NUMBER() OVER (PARTITION BY provider_id ORDER BY provider_name) AS RN
        FROM CTE)
    SELECT provider_id, provider_name
    FROM RNs
    WHERE RN = 1;

GO