我有几张桌子正在加入
organization table:
id, name
registration table:
id, name
执行此操作后,它的外观如何
org_id org_name reg_name reg_id
--------------------------------------------------------
329 abc regname1 311
329 abc regname2 298
我想要做的是显示数据ONE行,如下所示:
org_id org_name reg_name reg_id
------------------------------------------------------------------------
329 abc regname1;regname2 311;298
注意:我的reg_name是动态的,可能是一个或十个。
答案 0 :(得分:0)
您要找的是SQLCLR custom aggregator。然后,您将使用手工制作的自定义聚合器,就像使用SUM聚合器一样。
一个粗略的自定义聚合器,它将累积字符串,对它们进行排序,然后用分号连接,就像这样:
[Serializable]
[Microsoft.SqlServer.Server.SqlUserDefinedAggregate(Format.UserDefined, MaxByteSize=-1)]
public struct JoinString : IBinarySerialize
{
List<String> strings;
public void Init()
{
strings = new List<String>();
}
public void Accumulate(SqlString input)
{
strings.Add(input.Value);
}
public void Merge(JoinString Group)
{
strings.AddRange(Group.strings.ToArray());
}
public SqlString Terminate()
{
strings.Sort();
return new SqlString(String.Join(";", strings.ToArray()));
}
public void Read(System.IO.BinaryReader r)
{
int items = r.ReadInt32();
strings = new List<String>(items);
for (var i = 0; i < items; i++)
strings.Add(r.ReadString());
}
public void Write(System.IO.BinaryWriter w)
{
w.Write(strings.Count);
foreach (var s in strings)
w.Write(s);
}
}
答案 1 :(得分:0)
我想试试这篇文章:comma separated list in SQL-server。
答案 2 :(得分:0)
在Oracle中,您也可以使用list_aggr函数。 例如:
SELECT deptno, LISTAGG(ename, ',') WITHIN GROUP (ORDER BY ename) AS employees
FROM emp
GROUP BY deptno;
您的查询应该是:
SELECT a.org_id,a.org_nam, LISTAGG(reg_name, ';') WITHIN GROUP (ORDER BY a.org_id) AS reg_name, LISTAGG(reg_id, ';') WITHIN GROUP (ORDER BY a.org_id) AS reg_id
FROM organization a , registration b
where b.org_id = a.org_id
GROUP BY a.org_id,a.org_nam;