數據庫把n行查詢為1行
阿新 • • 發佈:2017-07-26
rom table int sys insert reat str ble acl
一、創建示例表
CREATE TABLE TestTable ( name VARCHAR(10), skill VARCHAR(10) ); INSERT INTO TestTable VALUES (‘張三‘, ‘php‘); INSERT INTO TestTable VALUES (‘張三‘, ‘java‘); INSERT INTO TestTable VALUES (‘張三‘, ‘c#‘); INSERT INTO TestTable VALUES (‘李四‘, ‘c‘); INSERT INTO TestTable VALUES (‘李四‘, ‘c++‘);
表結構為:
name | skill |
張三 | php |
張三 | java |
張三 | c# |
李四 | c |
李四 | c++ |
希望查詢的結果:
name | allSkill |
張三 | php,java,c# |
李四 | c,c++ |
二、SQL Server中實現
-- SQL Server SELECT name,STUFF( ( SELECT ‘,‘ + skill FROM testtable a WHERE a.name = b.name FOR XML PATH(‘‘) ), 1, 1, ‘‘) AS allSkill FROM testtable b GROUP BY name
三、MySQL中實現
-- MySQL SELECT name,GROUP_CONCAT(skill) AS allSkill FROM testtable GROUP BY name;
四、Oracle中實現
-- Oracle SELECT name,WMSYS.WM_CONCAT(skill) AS allSkill FROM testtable GROUP BY name;
數據庫把n行查詢為1行