将关联表展平为多值列?

时间:2012-03-19 23:50:10

标签: sql sql-server sql-server-2008 tsql

我有一张只包含产品ID和类别ID的表格(产品可以在多个类别中)。如何将类别ID展平到产品列中,以便我以此结束:

id | name | desc | categories
1 | test1 | lorem | 1,3,4,23
2 | test2 | ipsom | 4,6,24

就像我需要循环到categories列的单独表中一样。我怎么能这样做或有更好的方法吗?

4 个答案:

答案 0 :(得分:7)

我创建了一个CLR aggregate function,其中包含varchar列并返回以逗号分隔的所有值。换句话说,它将几个字符串连接到以逗号分隔的列表中。 我确信它的性能优于任何T-Sql技巧

作为任何聚合函数,它可以与group by结合使用。例如:

SELECT id, name, desc, JoinStrings(CONVERT(VARCHAR(20), category_id))
FROM product p
INNER JOIN category_products c ON p.category_id = c.category_id
GROUP BY id, name, desc

以下是在Cql Server 2008中创建CLR程序集的C#代码:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;


[Serializable]
[Microsoft.SqlServer.Server.SqlUserDefinedAggregate(Format.UserDefined, IsInvariantToDuplicates=false, IsInvariantToOrder=false, IsInvariantToNulls=true, MaxByteSize=-1)]
public struct JoinStrings : IBinarySerialize
{
    private char[] sb;
    private int pos;
    public void Init()
    {
        sb = new char[512000];
        pos = 0;
    }

    public void Accumulate(SqlString Value)
    {
        if (Value.IsNull) return;
        char[] src = Value.ToString().ToCharArray();
        Array.Copy(src, 0, sb, pos, src.Length);
        pos += src.Length;
        sb[pos] = ',';
        pos++;
    }

    public void Merge(JoinStrings Group)
    {
        Accumulate(Group.Terminate());
    }

    public SqlString Terminate()
    {
        if (pos <= 0) 
            return new SqlString();
        else
            return new SqlString(new String(sb, 0, pos-1));
    }

    public void Read(System.IO.BinaryReader r)
    {
        this.Init();
        pos = r.ReadInt32();
        r.Read(sb, 0, pos);
    }

    public void Write(System.IO.BinaryWriter w)
    {
        w.Write(pos);
        w.Write(sb, 0, pos);
    }
}

以下是创建该函数的代码(虽然从Visual Studio部署应该自动执行):

CREATE AGGREGATE [dbo].[JoinStrings]
(@s [nvarchar](4000))
RETURNS[nvarchar](max)
EXTERNAL NAME [YouAssemblyName].[JoinStrings]

答案 1 :(得分:1)

我建议使用Recursive CTE。我相信它会是这样的:

select productid, categoryid, 
    row_number() over (partition by id order by categoryid) as rownum
into #tabletorecurse
from TABLENAME

with finaloutput as
(
    select productid as id, name, desc, categoryid as categories, rownum
    from #tabletorecurse
        join PRODUCTTABLE
            on PRODUCTTABLE.id = #tabletorecurse.productid
    where rownum = 1

    union all

    select tr.id, tr.name, tr.desc, 
        finaloutput.categories + ', ' + tr.categoryid, tr.rownum
    from #tabletorecurse as tr
        join finaloutput 
            on finaloutput.rownum + 1 = tr.rownum 
                and finaloutput.id = tr.productid
)
select id, name, desc, categories
from finaloutput
    join 
    (
        select max(rownum) as maxrow, id
        from finaloutput
        group by id 
    ) as maxvalues
       on maxvalues.id = finaloutput.id 
           and maxvalues.maxrow = finaloutput.rownum

答案 2 :(得分:1)

在MSSQL中没有内置的方法。

Simulating group_concat MySQL function in Microsoft SQL Server 2005?很好地描述了如何实施变通方法。

答案 3 :(得分:1)

使用功能。
这会查找文本,因此您需要进行调整 COALESCE只是放一个,。
这是一个大规模的生产应用程序 - 它的工作原理很快 JustinPony对功能提出了质疑,因为功能很慢 我正在点击几百万条记录,但只返回100行 该功能仅适用于百行。

用法:

select top 5 sID, ( select [dbo].[JoinMVEnum](docSVsys.sID, '140') ) as [Flag Issue]
from docSVsys

功能

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[JoinMVText]
(
   @sID int,
   @fieldID tinyint
)
RETURNS VARCHAR(MAX)
AS 
BEGIN
    DECLARE @MVtextList varchar(max)
    SELECT @MVtextList = COALESCE(@MVtextList + '; ', '') + docMVtext.value
    FROM docMVtext with (nolock) 
    WHERE docMVtext.sID = @sID and fieldID = @fieldID
    RETURN @MVtextList
END

GO