以下脚本由成员(OMG Ponies)为the question i posted last nigh t撰写。 脚本中有语法错误我无法理解。有人可以试一试吗?它使用MS SQL Server 2000/2005/2008
select
'Steve' as name,
'4/20/1960' as DOB,
'12456' as agentID,
'Smith' as agentName
into #TABLE1
insert into #TABLE1
select
'Steve' as name,
'4/20/1960' as DOB,
'12456' as agentID,
'John' as agentName
insert into #TABLE1
select
'Steve' as name,
'4/20/1960' as DOB,
'12456' as agentID,
'Lary' as agentName
select * from #TABLE1
+---------+-----------+----------+------------------+ | Name | DOB | AgentID | AgentName | +---------+-----------+----------+------------------+ | Steve | 4/20/1960 | 12456 | John | +---------+-----------+----------+------------------+ | Steve | 4/20/1960 | 12456 | Lary | +---------+-----------+----------+------------------+ | Steve | 4/20/1960 | 12456 | Smith | +---------+-----------+----------+------------------+ +---------+-----------+----------+----------------------+ | Name | DOB | AgentID | AgentName | +---------+-----------+----------+----------------------+ | Steve | 4/20/1960 | 4444 | John,Larry, Smith | +---------+-----------+----------+----------------------+
SELECT DISTINCT
t.name,
t.dob,
t.agentid,
STUFF(ISNULL(SELECT ', ' + x.agentname
FROM TABLE1 x
WHERE x.agentid = t.agentid
GROUP BY x.agentname
FOR XML PATH ('')), ''), 1, 2, '')
FROM TABLE1 t
[错误]脚本行:1-10 ------------------------- 关键字'SELECT'附近的语法不正确。 消息:156,等级:15,状态:1,程序:,行:5
[错误]脚本行:1-10 ------------------------- ')'附近的语法不正确。 消息:102,等级:15,状态:1,程序:,行:9
答案 0 :(得分:0)
这是作品!
select 'Steve' as name, '4/20/1960' as DOB, '12456' as agentID, 'Smith' as agentName into #TABLE1
insert into #TABLE1 select 'Steve' as name, '4/20/1960' as DOB, '12456' as agentID, 'John' as agentName
insert into #TABLE1 select 'Steve' as name, '4/20/1960' as DOB, '12456' as agentID, 'Lary' as agentName
select * from #TABLE1
SELECT DISTINCT t.name, t.dob, t.agentid, STUFF(ISNULL((SELECT ', ' + x.agentname FROM #TABLE1 x WHERE x.agentid = t.agentid GROUP BY x.agentname FOR XML PATH ('')), ''), 1, 2, '') FROM #TABLE1 t
DROP TABLE #Table1
--+---------+-----------+----------+------------------+ | Name | DOB | AgentID | AgentName | +---------+-----------+----------+------------------+ | Steve | 4/20/1960 | 12456 | John |
--+---------+-----------+----------+------------------+ | Steve | 4/20/1960 | 12456 | Lary | +---------+-----------+----------+------------------+ | Steve | 4/20/1960 | 12456 | Smith | +---------+-----------+----------+------------------+
--+---------+-----------+----------+----------------------+ | Name | DOB | AgentID | AgentName | +---------+-----------+----------+----------------------+ | Steve | 4/20/1960 | 4444 | John,Larry, Smith | +---------+-----------+----------+----------------------+