这非常接近,但与“将多行连接成单个文本字符串”Concatenate many rows into a single text string?
的帖子不同但我需要的是,因为表/行有许多相同的名称,我只想显示DISTINCT名称。因此,在上述帖子和谷歌的帮助下,我能够将其拉下来......
171444 ACTIVE,ACTIVE,ACTIVE,ACTIVE,ACTIVE,ACTIVE,ACTIVE,ACTIVE
169171 RETIRED,RETIRED,RETIRED,RETIRED,RETIRED
173648 RETIRED,RETIRED,RETIRED,RETIRED,INELIGIBLE,INELIGIBLE
我想要的是:
171444 ACTIVE
169171 RETIRED
173648 RETIRED,INELIGIBLE
我想我已经钉了它:
Select distinct ST2.EmployeeID,
substring((Select DISTINCT (',' + ( ST1.AccrualStatus )) AS [text()]
From dbo.Plan2 ST1
Where ST1.EmployeeID = ST2.EmployeeID
For XML PATH ('')),2, 1000) [Plan2]
From dbo.Plan2 ST2
SUBSTRING中需要第二个DISTINCT,以确保我们只为每个值返回一个出现值。
答案 0 :(得分:1)
这个答案来自你上次的评论。
假设您的表格至少包含[EmployeeID]
列和[Statuses]
VARCHAR列,其宽度足以包含您的任意状态字符串(我认为它们是状态),你是什么可以做的是:
UPDATE OT1
SET OT1.[Statuses] = OT2.[text]
FROM [OtherTable] AS OT1
JOIN (
Select distinct ST2.EmployeeID,
substring((Select DISTINCT (',' + ( ST1.AccrualStatus )) AS [text()]
From dbo.Plan2 ST1
Where ST1.EmployeeID = ST2.EmployeeID
For XML PATH ('')),2, 1000) [Plan2]
From dbo.Plan2 ST2
) AS OT2([EmployeeID],[text])
ON OT1.[EmployeeID] = OT2.[EmployeeID];
我希望这有效。
答案 1 :(得分:-1)
CREATE TABLE T2
(
pr VARCHAR(20) ,
pt VARCHAR(20) ,
qty INT
);
INSERT INTO T2
( pr, pt, qty )
VALUES ( 'A', 'x1', 10 ),
( 'A', 'x2', 12 ),
( 'A', 'x1', 15 ),
( 'B', 'x1', 1 ),
( 'B', 'x5', 5 ),
( 'C', 'x5', 8 );
SELECT g1.pt ,
SUM(qty) AS SumQty ,
STUFF(( SELECT DISTINCT
', ' + g.pr
FROM T2 g
WHERE g.pt = g1.pt
FOR
XML PATH('')
), 1, 1, '') AS pr
FROM T2 g1
GROUP BY g1.pt
CREATE TABLE T2
(
pr VARCHAR(20) ,
pt VARCHAR(20) ,
qty INT
);
INSERT INTO T2
( pr, pt, qty )
VALUES ( 'A', 'x1', 10 ),
( 'A', 'x2', 12 ),
( 'A', 'x1', 15 ),
( 'B', 'x1', 1 ),
( 'B', 'x5', 5 ),
( 'C', 'x5', 8 );
SELECT g1.pt ,
SUM(qty) AS SumQty ,
STUFF(( SELECT DISTINCT
', ' + g.pr
FROM T2 g
WHERE g.pt = g1.pt
FOR
XML PATH('')
), 1, 1, '') AS pr
FROM T2 g1
GROUP BY g1.pt
结果:
x1 ------------------ 26 ------------------ A,B
x-------- ------------------ 12 ------------------ A
x5 ------------------ 13 ------------------- B,C