我想知道将以下行中的数据合并到另一个视图中的单个行的最佳方法。
这些是当前显示的结果;
Type_ID | Client_ID | PBX_Vendor |
127 | 090820006311404926326C | Aastra |
127 | 090820006311404926326C | Ericsson |
127 | 111012237401404926326C | Aastra |
127 | 120209287521404926326C | Aastra |
127 | 120209287521404926326C | Alcatel |
以下是我希望看到的数据;
Type_ID | Client_ID | PBX_Vendor |
127 | 090820006311404926326C | Aastra, Ericsson |
127 | 111012237401404926326C | Aastra |
127 | 120209287521404926326C | Aastra, Alcatel |
基本上,有多个PBX供应商与客户端ID相关联。对于服务台系统,我需要在一行中显示这个显示。
我已经尝试过使用CONCAT了,但我最终得到的只是一行,其中有超过100个供应商并非特定于Client_ID。
非常感谢任何帮助!
答案 0 :(得分:7)
这是 A 的方法(也适用于2005年):
表格强>
DECLARE @table TABLE
(
[Type_ID] INT,
[Client_ID] VARCHAR(50),
[PBX_Vendor] VARCHAR(50)
)
数据强>
INSERT INTO @table
SELECT 127,
'090820006311404926326C',
'Aastra'
UNION ALL
SELECT 127,
'090820006311404926326C',
'Ericsson'
UNION ALL
SELECT 127,
'111012237401404926326C',
'Aastra'
UNION ALL
SELECT 127,
'120209287521404926326C',
'Aastra'
UNION ALL
SELECT 127,
'120209287521404926326C',
'Alcatel'
<强>查询强>
SELECT [Type_ID],
[Client_ID],
(
SELECT STUFF((
SELECT ',' + [PBX_Vendor]
FROM @table
WHERE [Client_ID] = tbl.[Client_ID]
AND [Type_ID] = tbl.[Type_ID]
GROUP BY [PBX_Vendor]
ORDER BY [PBX_Vendor]
FOR
XML PATH('')
), 1, 1, '')
) PBX_Vendor
FROM @table tbl
GROUP BY [Type_ID],
[Client_ID]
<强>结果强>
Type_ID Client_ID PBX_Vendor
127 090820006311404926326C Aastra,Ericsson
127 111012237401404926326C Aastra
127 120209287521404926326C Aastra,Alcatel
答案 1 :(得分:0)
DECLARE @table TABLE
(
[Type_ID] INT,
[Client_ID] VARCHAR(50),
[PBX_Vendor] VARCHAR(50)
)
INSERT INTO @table
SELECT dbo.AMGR_User_Fields_Tbl.Type_Id, dbo.AMGR_User_Fields_Tbl.Client_Id, dbo.AMGR_User_Field_Defs_Tbl.Description AS PBX_Vendor
FROM dbo.AMGR_User_Fields_Tbl INNER JOIN
dbo.AMGR_User_Field_Defs_Tbl ON dbo.AMGR_User_Fields_Tbl.Type_Id = dbo.AMGR_User_Field_Defs_Tbl.Type_Id AND
dbo.AMGR_User_Fields_Tbl.Code_Id = dbo.AMGR_User_Field_Defs_Tbl.Code_Id
WHERE (dbo.AMGR_User_Fields_Tbl.Type_Id = 127)
SELECT [Type_ID],
[Client_ID],
(
SELECT STUFF((
SELECT ', ' + [PBX_Vendor]
FROM @table
WHERE [Client_ID] = tbl.[Client_ID]
AND [Type_ID] = tbl.[Type_ID]
GROUP BY [PBX_Vendor]
ORDER BY [PBX_Vendor]
FOR
XML PATH('')
), 1, 1, '')
) PBX_Vendor
FROM @table tbl
GROUP BY [Type_ID],
[Client_ID]