如何根据另一个表中的通用值在新表中创建多行?
ProviderTable: PersonTable:
-------------------- ---------------------
ProviderID | GroupID PersonID | ProviderID
1 | A 100 | 1
2 | A 101 | 3
3 | A 102 | 8
4 | NULL 103 | 10
5 | B 104 | 5
6 | C 105 | 4
7 | B
8 | NULL
9 | NULL
10 | C
ProviderTable.ProviderID = PersonTable.ProviderID
我需要为每个提供程序创建一个新表,其中包含一个人员行,其中 Provider.GroupID =Provider.GroupID
我正在寻找的结果:
New-table:
PersonID | ProviderID
100 | 1
100 | 2
100 | 3
101 | 3
101 | 1
101 | 2
102 | 8
103 | 10
103 | 6
104 | 5
104 | 7
105 | 4
此快速版本获取您正在寻找的排序顺序。测试数据包括:
DECLARE @pt table (
ProviderId int,
GroupId varchar(2)
)
DECLARE @pet table (
PersonId int,
ProviderId int
)
INSERT INTO @pt Values
(1,'A'),
(2,'A'),
(3,'A'),
(4,NULL),
(5,'B'),
(6,'C'),
(7,'B'),
(8,NULL),
(9,NULL),
(10,'C')
INSERT INTO @pet VALUES
(100,1),
(101,3),
(102,8),
(103,10),
(104,5),
(105,4)
SELECT pe.PersonId,
IsNull(p2.ProviderId, p1.providerId) As ProviderId
FROM @pt p1
INNER JOIN @pet pe
ON p1.ProviderId = pe.ProviderId
LEFT JOIN @pt p2
ON p1.GroupId = p2.GroupId
ORDER BY pe.personId,
CASE
WHEN pe.ProviderId = p2.ProviderId
Then 0
ELSE 1
END
您可以使用
以下 SQL 语句:
SELECT PER.PersonID, COALESCE(PG.ProviderID, PP.ProviderID) AS ProviederID
FROM PersonTable PER
INNER JOIN ProviderTable PP
ON PP.ProviderID = PER.ProviderID
LEFT OUTER JOIN ProviderTable PG
ON PG.GroupID = PP.GroupID;