SQL 怎么把列的值组合?
SQL 按类型怎么把列的值组合?
例:列值
类型 列值
A 1
A 2
A 3
B 1
B 2
要求显示值为:
类型 列值
A 1,2,3
B 1,2
列值中间加,号字符
------解决方案--------------------
with tb(a,b) as
(
select 'a','1' union all
select 'a','2' union all
select 'a','3' union all
select 'b','1' union all
select 'b', '2')
select A,stuff((select ','+b from tb where A=a.a for xml path('')),1,1,'')as b from tb a group by a
------解决方案--------------------写个CLR聚合函数就可以了
网上很多例子:如最多的这个STRJOIN就是了
编译一下就可以运行了
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Text;
[Serializable]
[Microsoft.SqlServer.Server.SqlUserDefinedAggregate(Format.UserDefined,
IsInvariantToDuplicates = false,
IsInvariantToNulls = true,
IsInvariantToOrder = false,
IsNullIfEmpty = true,
MaxByteSize = 8000
,Name="concate"
)]
public struct StrJoin : IBinarySerialize
{
private StringBuilder _result;
public void Init()
{
_result = new StringBuilder();
}
public void Accumulate(SqlString Value)
{
if (Value.IsNull)
{
return;
}
else
{
if (_result.Length > 0)
_result.Append(",");
_result.Append(Value.Value);
}
}
public void Merge(StrJoin Group)
{
_result.Append(Group._result);
}
public SqlString Terminate()
{
if (_result.Length > 0)
{
return new SqlString(_result.ToString());
}
return new SqlString("");
}
#region IBina