我得到了两个表,其中的数据如下:
表1:学生
表2:主题
我需要输出为:
我通过使用 XML PATH 的以下查询实现了此目的
代码:
WITH cte
AS ( SELECT Stu.Student_Id ,
Stu.Student_Name ,
( SELECT Sub.[Subject] + ','
FROM [Subject] AS Sub
WHERE Sub.Student_Id = Stu.Student_Id
ORDER BY Sub.[Subject]
FOR
XML PATH('')
) AS [Subjects]
FROM dbo.Student AS Stu
)
SELECT Student_id [Student Id] ,
student_name [Student Name] ,
SUBSTRING(Subjects, 1, ( LEN(Subjects) - 1 )) AS [Student Subjects]
FROM cte
我的问题是有没有更好的方法来做到这一点而不使用 XML 路径?
最佳答案
这是一个非常好的方法,并且已经被广泛接受。有几种方法,这个 blog post描述了其中很多。
现有的一种有趣的方法是使用 CLR 来为您完成工作,这将显着降低查询的复杂性,但需要权衡运行外部代码。下面是该类在程序集中的示例。
using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.IO;
using Microsoft.SqlServer.Server;
[Serializable]
[SqlUserDefinedAggregate(Format.UserDefined, MaxByteSize=8000)]
public struct strconcat : IBinarySerialize{
private List values;
public void Init() {
this.values = new List();
}
public void Accumulate(SqlString value) {
this.values.Add(value.Value);
}
public void Merge(strconcat value) {
this.values.AddRange(value.values.ToArray());
}
public SqlString Terminate() {
return new SqlString(string.Join(", ", this.values.ToArray()));
}
public void Read(BinaryReader r) {
int itemCount = r.ReadInt32();
this.values = new List(itemCount);
for (int i = 0; i <= itemCount - 1; i++) {
this.values.Add(r.ReadString());
}
}
public void Write(BinaryWriter w) {
w.Write(this.values.Count);
foreach (string s in this.values) {
w.Write(s);
}
}
}
这将使查询更像这样。
SELECT CategoryId,
dbo.strconcat(ProductName)
FROM Products
GROUP BY CategoryId ;
这显然要简单一些。物有所值:)
美好的一天!
关于sql-server-2008 - 逗号分隔结果集 + SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12065594/