我见过多个将单列卷成逗号分隔列表的示例,但我需要更多。
这是我需要的数据和结果的示例。
DECLARE @SalesPerson table (SalesPersonID int, SalesPersonName varchar(10))
DECLARE @Region table (RegionID int, RegionName varchar(15))
DECLARE @SalesPersonRegion table (SalesPersonID int, RegionID int)
INSERT INTO @SalesPerson (SalesPersonID, SalesPersonName) VALUES (1,'Jeff')
INSERT INTO @SalesPerson (SalesPersonID, SalesPersonName) VALUES (2,'Pat')
INSERT INTO @SalesPerson (SalesPersonID, SalesPersonName) VALUES (3,'Joe')
INSERT INTO @Region (RegionID, RegionName) VALUES (1,'North')
INSERT INTO @Region (RegionID, RegionName) VALUES (2,'South')
INSERT INTO @Region (RegionID, RegionName) VALUES (3,'East')
INSERT INTO @Region (RegionID, RegionName) VALUES (4,'West')
INSERT INTO @SalesPersonRegion (SalesPersonID,RegionID) VALUES (1,1)
INSERT INTO @SalesPersonRegion (SalesPersonID,RegionID) VALUES (1,2)
INSERT INTO @SalesPersonRegion (SalesPersonID,RegionID) VALUES (1,3)
INSERT INTO @SalesPersonRegion (SalesPersonID,RegionID) VALUES (2,2)
INSERT INTO @SalesPersonRegion (SalesPersonID,RegionID) VALUES (2,3)
INSERT INTO @SalesPersonRegion (SalesPersonID,RegionID) VALUES (2,4)
INSERT INTO @SalesPersonRegion (SalesPersonID,RegionID) VALUES (3,1)
INSERT INTO @SalesPersonRegion (SalesPersonID,RegionID) VALUES (3,4)
一个简单的选择将使我得到每个销售人员,每个销售人员所在的区域。
SELECT
sp.SalesPersonID,
sp.SalesPersonName,
r.RegionName
FROM @SalesPersonRegion spr
JOIN @SalesPerson sp
ON spr.SalesPersonID = sp.SalesPersonID
JOIN @Region r
ON spr.RegionID = r.RegionID
在这种情况下,它将返回 9 行。
我想得到这样的结果:
SalesPersonID SalesPersonName Regions
1 Jeff North,South,East
2 Pat South,East,West
3 Joe North,West