在单行中滚动多行

时间:2016-06-15 05:03:14

标签: sql sql-server-2008 tsql

我正在尝试合并员工数据库表的行

这是我的原始表

enter image description here

我想根据部门合并行。这是我的预期结果。

enter image description here

我尝试使用FOR XML PATH('')),1,1,'')但我只能列出一列。

我知道我们有类似的问题here,但它只有一列。

非常感谢任何帮助

3 个答案:

答案 0 :(得分:1)

只需对其他列使用相同的方法:

SELECT
    t.Department,
    Worker = 
        STUFF((
            SELECT ';' + Worker
            FROM tbl 
            WHERE Department = t.Department
            ORDER BY Worker
            FOR XML PATH(''), TYPE
        ).value('text()[1]','NVARCHAR(MAX)'), 1, 1, N''),
    Phone = 
        STUFF((
            SELECT ';' + Phone
            FROM tbl 
            WHERE Department = t.Department
            ORDER BY Worker
            FOR XML PATH(''), TYPE
        ).value('text()[1]','NVARCHAR(MAX)'), 1, 1, N''),
    Ext = 
        STUFF((
            SELECT ';' + Ext
            FROM tbl 
            WHERE Department = t.Department
            ORDER BY Worker
            FOR XML PATH(''), TYPE
        ).value('text()[1]','NVARCHAR(MAX)'), 1, 1, N'')
FROM tbl t
GROUP BY t.Department

答案 1 :(得分:0)

您也可以尝试以下查询:

SELECT
    t.Department,
    Worker = STUFF((
                SELECT ';' + s.Worker
                FROM
                    YourTable s
                WHERE
                    s.Department = t.Department
                FOR XML PATH('')),1,1,''),
    Phone = STUFF((
                SELECT ';' + CAST(s.Phone AS VARCHAR(25))
                FROM
                    YourTable s
                WHERE
                    s.Department = t.Department
                FOR XML PATH('')),1,1,''),
    Ext = STUFF((
                SELECT ';' + CAST(s.Ext AS VARCHAR(25))
                FROM
                    YourTable s
                WHERE
                    s.Department = t.Department
                FOR XML PATH('')),1,1,'')
FROM YourTable t
GROUP BY t.Department

答案 2 :(得分:0)

我刚刚在网上找到这个。我试过了,它对我很有用。试一试,看看你是如何相处的。

http://groupconcat.codeplex.com/

http://groupconcat.codeplex.com/releases/view/618110

创建TABLE测试表(     客户VARCHAR(50),     产品VARCHAR(50),     方法VARCHAR(50),     INDEX ix CLUSTERED(客户) )

INSERT INTO testtable(客户,产品,方法) VALUES     (' John',' Computer',' Credit'),     (' John',' Mouse',' Cash'),     (' Will',' Computer',' Credit'),     (' Will',' Mouse',' Cash'),     (' Will',' Speaker',' Cash'),     (' Todd',' Computer',' Credit')

选择* 来自testtable

SELECT Customer,dbo.GROUP_CONCAT(product),dbo.GROUP_CONCAT(method) 来自testtable GROUP BY客户

enter image description here