--創建測試表 IF OBJECT_ID('test') IS NOT NULL DROP TABLE test CREATE TABLE dbo.test( id int IDENTITY(1,1) NOT NULL, name varchar(50) NULL, subject varchar(50) NULL, source decimal(18,2) NULL ) GO --插入測試數據 INSERT INTO test (name,subject,source) SELECT '張三','語文',60 UNION ALL SELECT '張三','英語',90 UNION ALL SELECT '李四','語文',70 UNION ALL SELECT '李四','數學',80 UNION ALL SELECT '王五','數學',75 UNION ALL SELECT '王五','英語',80 GO SELECT * FROM test --1 通過 select 累加 DECLARE @sql_col VARCHAR(8000) SELECT @sql_col = ISNULL(@sql_col + ',','') + QUOTENAME(Subject) FROM test GROUP BY Subject SELECT @sql_col --2 通過 FOR xml path('') 合並字符串記錄 SELECT STUFF( (SELECT '#' + Subject FROM test WHERE name = '王五' FOR xml path('') ),1,1,'' ) --3 分組合並字符串記錄 SELECT name, Subject = ( STUFF( (SELECT '#' + Subject FROM test WHERE name = A.name FOR xml path('') ),1,1,'' ) ) FROM test A GROUP by name
