按组工作,将数据分组为字符串格式

时间:2010-05-20 07:07:46

标签: sql-server tsql group-by sql

我有一张表格,其中包含下面给出的一些数据。它使用树状结构

即。

                Department

     SubD1,                       SubD2 .....

PreSubD1, PreSubD1...       PreSubD2, PreSubD2...       

pk_map_id            preferences          ImmediateParent      Department_Id
-------------------- -------------------- -------------------- --------------------
20                   14                   5                    1
21                   15                   5                    1
22                   16                   6                    1
23                   9                    4                    2
24                   4                    3                    2
25                   24                   20                   2
26                   25                   20                   2
27                   23                   13                   2

我想代表部门分组我的记录,然后是直接父母,然后将每个首选项分隔为','

即。

department  Immediate Parent  preferences
1             5,6                 14,15,16
2             4,3,20,13           9,4,24,25,23

and this table also

Immediate parent  preferences
5                     14,15
6                     16
4                     9
3                     4
20                    24,25
13                    13

在实际场景中,所有这些都是我的ID,它们将被字符串字段替换。

我使用的是SQL Server 2k5

1 个答案:

答案 0 :(得分:2)

您可以在子查询中使用FOR XML PATH来获取逗号分隔的值列表。然后你对你的关键字段进行GROUP BY,以获得正确的值。

第一次查询

SELECT
    [Department_Id],
    STUFF(
    (
        SELECT
            ',' + CONVERT(varchar(10), [ImediateParent])
        FROM
            [YourTable] [YourTable2]
        WHERE
            [YourTable2].[Department_Id] = [YourTable].[Department_Id]
        FOR XML PATH('')
    ), 1, 1, ''),
    STUFF(
    (
        SELECT
            ',' + CONVERT(varchar(10), [Preferences])
        FROM
            [YourTable] [YourTable2]
        WHERE
            [YourTable2].[Department_Id] = [YourTable].[Department_Id]
        FOR XML PATH('')
    ), 1, 1, '')
FROM
    [YourTable]
GROUP BY
    [YourTable].[Department_Id]

以及第二次查询

SELECT
    [ImediateParent],
    STUFF(
    (
        SELECT
            ',' + CONVERT(varchar(10), [Preferences])
        FROM
            [YourTable] [YourTable2]
        WHERE
            [YourTable2].[ImediateParent] = [YourTable].[ImediateParent]
        FOR XML PATH('')
    ), 1, 1, '')
FROM
    [YourTable]
GROUP BY
    [YourTable].[ImediateParent]