如何连接多行的列值
表A
FName LName amount Id
---------------------
A B 100 1
A B 200 2
A C 400 3
A B 300 4
我需要结果如:
FName LName totalAmount count Id
------------------------------------
A B 600 3 1,2,4
A C 400 1 3
如何获得它?
请帮助我....
谢谢&此致
比涅塔..
答案 0 :(得分:1)
DECLARE @TABLE_A TABLE
(FName VARCHAR(10), LName VARCHAR(10), amount INT, Id INT)
INSERT INTO @TABLE_A VALUES
('A','B',100,1),
('A','B',200,2),
('A','C',400,3),
('A','B',300,4)
SELECT A.FName
,A.LName
,SUM(A.amount) AS totalAmount
,COUNT(*) AS [COUNT]
,STUFF((
SELECT ',' + CAST(ID AS NVARCHAR(10))
FROM @TABLE_A
WHERE FName = A.FName AND LName = A.LName
FOR XML PATH(''),TYPE).value('.','NVARCHAR(MAX)'),1,1,'') AS ID
FROM @TABLE_A A
GROUP BY A.FName
,A.LName
╔═══════╦═══════╦═════════════╦═══════╦══════════╗
║ FName ║ LName ║ totalAmount ║ COUNT ║ ID ║
╠═══════╬═══════╬═════════════╬═══════╬══════════╣
║ A ║ B ║ 600 ║ 3 ║ 1,2,4 ║
║ A ║ C ║ 400 ║ 1 ║ 3 ║
╚═══════╩═══════╩═════════════╩═══════╩══════════╝
SQL FIDDLE