T-SQL GROUP BY - 在结果中列出而不是聚合函数

时间:2013-12-30 20:21:41

标签: sql-server tsql group-by

有没有办法在T-SQL中使用GROUP BY但是得到“join-list”而不是agregate函数? 例如:

-- this table
CREATE TABLE tblDATA(
    Name int,
    GroupName nvarchar(50)
)

-- with this data
INSERT INTO tblDATA VALUES('Peter', 'A')
INSERT INTO tblDATA VALUES('Peter', 'B')
INSERT INTO tblDATA VALUES('Jane', 'A')
INSERT INTO tblDATA VALUES('Jane', 'C')
INSERT INTO tblDATA VALUES('Jane', 'D')
INSERT INTO tblDATA VALUES('Dave', 'B')
INSERT INTO tblDATA VALUES('Susan', 'E')
INSERT INTO tblDATA VALUES('Susan', 'F')


-- and get this query result in the two collumns (I don't care about delimiter) :
Peter       A, B
Jane        A, C, D
Dave        B
Susan       E, F

1 个答案:

答案 0 :(得分:2)

测试数据

CREATE TABLE #tblDATA(
    Name VARCHAR(20),     --<-- Your Name column is defined as INT Data Type 
    GroupName nvarchar(50)
)

-- with this data
INSERT INTO #tblDATA VALUES('Peter', 'A')
INSERT INTO #tblDATA VALUES('Peter', 'B')
INSERT INTO #tblDATA VALUES('Jane', 'A')
INSERT INTO #tblDATA VALUES('Jane', 'C')
INSERT INTO #tblDATA VALUES('Jane', 'D')
INSERT INTO #tblDATA VALUES('Dave', 'B')
INSERT INTO #tblDATA VALUES('Susan', 'E')
INSERT INTO #tblDATA VALUES('Susan', 'F')

<强>查询

SELECT DISTINCT Name, STUFF(List.Groups, 1 ,2 , '') AS Groups
FROM #tblDATA t  
            CROSS APPLY (
                        SELECT ', ' + GroupName [text()]
                        FROM #tblDATA
                        WHERE Name = t.Name
                        FOR XML PATH('')
                        )List(Groups)

结果集

╔═══════╦═════════╗
║ Name  ║ Groups  ║
╠═══════╬═════════╣
║ Dave  ║ B       ║
║ Jane  ║ A, C, D ║
║ Peter ║ A, B    ║
║ Susan ║ E, F    ║
╚═══════╩═════════╝