连接多行

时间:2010-07-07 18:15:18

标签: sql sql-server sql-server-group-concat

我正在使用Microsoft SQL Server 2005。

我想我需要一个子查询。

我正在为每个客户寻找一(1)行,其中AvailableAction字段是每个客户的所有操作的串联。

use tempdb
GO
IF DB_ID('myDatabase') IS NOT NULL
  DROP DATABASE myDatabase
go
CREATE DATABASE myDatabase 
GO
USE myDatabase
GO
create table Cust(
CustID Int Identity Primary Key,
CustName Varchar(255)
)
GO
INSERT INTO Cust(CustName) values('One')
INSERT INTO Cust(CustName) values('Two')
GO
CREATE TABLE Action(
ActionID Int Identity(101,1) Primary Key,
ActionName Varchar(128)
)
GO
INSERT INTO Action(ActionName) VALUES('Insert')
INSERT INTO Action(ActionName) VALUES('Update')
INSERT INTO Action(ActionName) VALUES('Delete')
INSERT INTO Action(ActionName) VALUES('Print')
GO
create table CustAction(
CustActionID Int Identity Primary Key,
CustID Int,
ActionID Int
)
GO
INSERT INTO CustAction(CustID,ActionID) VALUES(1,101)
INSERT INTO CustAction(CustID,ActionID) VALUES(1,102)
INSERT INTO CustAction(CustID,ActionID) VALUES(2,102)
INSERT INTO CustAction(CustID,ActionID) VALUES(2,103)
GO
SELECT Cust.CustID,CustName,ActionName
FROM CustAction
JOIN Cust
ON CustAction.CustID = Cust.CustID
JOIN Action
ON CustAction.ActionID = Action.ActionID
GO
SELECT 
Cust.CustID,CustName,
'<option value="' + CAST(Action.ActionID AS Varchar) + '">' + ActionName + '</option>' AS AvailableAction
FROM CustAction
JOIN Cust
ON CustAction.CustID = Cust.CustID
JOIN Action
ON CustAction.ActionID = Action.ActionID

我希望输出为:

CustID AvailableAction

    1  <option value="101">Insert</option><option value="102">Update</option>
    2  <option value="102">Update</option><option value="103">Delete</option>

2 个答案:

答案 0 :(得分:3)

2005 +

SELECT CustID
     , (SELECT ca.ActionID [@value]
             , ActionName [text()]
          FROM dbo.CustAction ca
         INNER JOIN dbo.Action ON ca.ActionID = Action.ActionID
         WHERE ca.CustID = c.CustID
           FOR XML PATH('option'), TYPE) AvailableAction
  FROM dbo.Cust c

我认为你不能用FOR XML EXPLICIT来获得这个,所以如果这是2000,那你就不走运了(就简单的解决方案而言)。

答案 1 :(得分:1)

这种方式我肯定会被了解SQL Server XML的人更好!

 SELECT CustID  ,
       CustName,
       REPLACE(REPLACE(
       ( SELECT '<option value="' + CAST(ACTION.ActionID AS VARCHAR) + '">' + ActionName + '</option>'
       FROM    ACTION
               JOIN CustAction
               ON      CustAction.CustID = Cust.CustID
       WHERE   CustAction.ActionID       = ACTION.ActionID FOR XML PATH('')
       )
       ,'&lt;','<'),'&gt;','>') AvailableAction
FROM   Cust