怎么把多行数据按照id合并为一行?SQL语句应该如何写啊?在线急求。
id name
TB7629 轻度脂肪肝
TB7629 右肾囊肿直径25px
TB10256 未见异常
TP36 脂肪肝
TP36 胆囊壁胆固醇结晶
TP36 左肾囊肿直径20px
我想通过SQL语句,得到以下结果:
id name
TB7629 轻度脂肪肝,右肾囊肿直径25px
TB10256 未见异常
TP36 脂肪肝, 胆囊壁胆固醇结晶, 左肾囊肿直径20px。
由于数据比较多,最好要能批量处理的语句。 展开
--sql2000
Create Function fn_hb(@id Varchar(100))
Returns Varchar(8000)
As
Begin
Declare @Rst Varchar(8000)
Set @Rst=''
Select @Rst=@Rst+name+',' From test Where id=@id
Set @Rst=Left(@Rst,len(@RSt)-1)
Return @Rst
End
go
--调用
select id,dbo.fn_hb(id) As 名称 from test
Group by id
--sql2005+
Select id,
Stuff(
(Select ','+name From test Where id=A.id
For XML Path('')
),1,1,'') As name
From test A
Group by id
这个是在SQL Sever 2005中运行吗?Access数据库可以不?
Access?我百度来的,你看行不行
在 Access的模块中建立一个自定义函数:
public Function CombStr(TableName As String, FieldName As String, GroupField As String, GroupValue As String) As String
Dim ResultStr As String
Dim rs As Recordset
Set rs = CurrentDb.OpenRecordset(" select " & FieldName & " from " & TableName & " where " & GroupField & "='" & GroupValue & "'")
If rs.RecordCount > 0 Then
Do While Not rs.EOF
ResultStr = ResultStr & "," & rs.Fields(0).Value
rs.MoveNext
Loop
End If
If ResultStr <> "" Then ResultStr = Mid(ResultStr, 2)
CombStr = ResultStr
End Function
建立查询:
select T.comname, combstr("T","Name","comname",t.comname) AS CombName, combstr("T","ses","comname",t.comname) AS CombSex
FROM T
GROUP BY T.comname
我根据网上的提示,采用了SELECT id, [name]=STUFF((SELECT ','+[name] FROM test t WHERE id=test.id FOR XML PATH('')), 1, 1, '')
FROM test GROUP BY id; 等几种语句,可是总是运行不了。对这个语句不是很懂,希望能有针对这个写好的语句