查询以连接SQL Server 2008 R2多行的列值

时间:2014-08-23 06:01:41

标签: sql-server tsql sql-server-2008-r2

如何连接多行的列值

表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

如何获得它?

请帮助我....

谢谢&此致

比涅塔..

1 个答案:

答案 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