我有两个表,一个包含员工列表,另一个包含PO列表。
PO表如下:
PoID PO# Name City State
1 55 Jasons Company Miami FL
2 66 Mikes Company NewYork NY
3 77 Sallys Company Dallas TX
我的员工表看起来像:
EmployeeID Name Phone Email PoID
1 John 123-123-1233 j@j.com 1
2 Alex 234-234-2344 a@a.com 1
3 Cindy 345-345-3455 c@c.com 2
4 Jessica 356-356-3566 j@j.com 3
现在我的SQL Select语句是这样的:
SELECT * FROM PO p
LEFT JOIN Employees e
ON p.PoID = e.PoID
它将返回我的PO表中的所有记录,也许只是与该记录关联的任何员工的最高条目。我还需要提取所有相关记录的名称/电子邮件。
我不确定如何实现这一目标,因为我不想要重复的PO条目,而只是一个以逗号分隔的列表,列出与该PO关联的任何可能的名称/电子邮件,以便在我的PO中添加两个额外的列
希望这是有道理的,如果有人遇到过这种情况,那么您的见解将受到赞赏。
答案 0 :(得分:2)
您可以尝试此查询
SELECT p.*,
STUFF((SELECT DISTINCT ',' + Name
FROM @Employees e1
WHERE e1.PoID = p.PoID
FOR XML PATH (''))
, 1, 1, '') AS Names
,STUFF((SELECT DISTINCT ',' + Phone
FROM @Employees e1
WHERE e1.PoID = p.PoID
FOR XML PATH (''))
, 1, 1, '') AS Phones
,STUFF((SELECT DISTINCT ',' + Email
FROM @Employees e1
WHERE e1.PoID = p.PoID
FOR XML PATH (''))
, 1, 1, '') AS Emails
FROM @PO p
结果
下面您可以看到包含测试数据的整个脚本
declare @po table(PoID int, PO int, Name varchar(100),City varchar(100),State varchar(100))
insert into @po
select 1,55,'Jasons Company','Miami','FL' union
select 2,66,'Mikes Company','NewYork','NY' union
select 3,77,'Sallys Company','Dallas','TX'
declare @Employees table(EmployeeID int, Name varchar(100),Phone varchar(100),Email varchar(100), PoID int)
insert into @Employees
select 1,'John','123-123-1233','j@j.com',1 union
select 2,'Alex','234-234-2344','a@a.com',1 union
select 3,'Cindy','345-345-3455','c@c.com',2 union
select 4,'Jessica','356-356-3566','j@j.com',3
SELECT p.*,
STUFF((SELECT DISTINCT ',' + Name
FROM @Employees e1
WHERE e1.PoID = p.PoID
FOR XML PATH (''))
, 1, 1, '') AS Names
,STUFF((SELECT DISTINCT ',' + Phone
FROM @Employees e1
WHERE e1.PoID = p.PoID
FOR XML PATH (''))
, 1, 1, '') AS Phones
,STUFF((SELECT DISTINCT ',' + Email
FROM @Employees e1
WHERE e1.PoID = p.PoID
FOR XML PATH (''))
, 1, 1, '') AS Emails
FROM @PO p
答案 1 :(得分:2)
你可以使用它。
DECLARE @PO TABLE (PoID INT, PO INT, Name VARCHAR(20), City VARCHAR(20), State vARCHAR(10))
INSERT INTO @PO
VALUES
(1, 55, 'Jasons Company','Miami','FL'),
(2, 66, 'Mikes Company','NewYork','NY'),
(3, 77, 'Sallys Company','Dallas','TX')
DECLARE @Employees TABLE (EmployeeID INT, Name VARCHAR(20), Phone VARCHAR(20), Email VARCHAR(20), PoID INT)
INSERT INTO @Employees
VALUES
(1,'John','123-123-1233','j@j.com',1 ),
(2,'Alex','234-234-2344','a@a.com',1),
(3,'Cindy','345-345-3455','c@c.com',2),
(4,'Jessica','356-356-3566','j@j.com',3)
SELECT
*,
STUFF ( (SELECT
', ' + Name + '/' + Email
FROM
@Employees e WHERE e.PoID = p.PoID FOR XML PATH('') ) ,1,1,'') [names/emails]
FROM
@PO p
结果
PoID PO Name City State names/emails
----------- ----------- -------------------- -------------------- ---------- -------------------
1 55 Jasons Company Miami FL John/j@j.com, Alex/a@a.com
2 66 Mikes Company NewYork NY Cindy/c@c.com
3 77 Sallys Company Dallas TX Jessica/j@j.com