如果有一个名为Employee的表EmpID EmpName---------- -------------1 Mary1 John1 Sam2 Alaina2 Edward我需要这种格式的结果:EmpID EmpName---------- -------------1 Mary, John, Sam2 Alaina, Edward问:这个记录是一样的。Employee桌子。我几乎没有使用UDF,存储过程的经验,我需要通过查询来完成这件事,这不可能不使用UDF,SP的。
3 回答
PIPIONE
TA贡献1829条经验 获得超9个赞
CREATE table #temp (EmpId INT, EmpName VARCHAR(100));WITH N(N)AS (SELECT 1 FROM(VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1))M(N)) ,tally(N)AS(SELECT ROW_NUMBER()OVER(ORDER BY N.N)FROM N,N a,N b,N c,N d,N e,N f)INSERT #tempSELECT EmpId, EmpName FROM (values(1, 'M ary'),(1, 'John'),(1, 'Sam')) x(EmpId, EmpName)CROSS APPLY (SELECT top 2000 N FROM tally) yUNION ALLSELECT EmpId, EmpName FROM (valu es(2, 'Alaina'),(2, 'Edward')) x(EmpId, EmpName)CROSS APPLY(SELECT top 2000 N FROM tally) y
SELECT distinct EmpId, ( SELECT EmpName+',' FROM #temp t2 WHERE t2.EmpId = t1.EmpId FOR XML PATH('') ) ConcatenatedFROM #temp t1
;WITH CTE as( SELECT distinct EmpId FROM #temp)SELECT EmpId, STUFF(( SELECT ','+EmpName FROM #temp t2 WHERE t2.EmpId = t1.EmpId FOR XML PATH('') ), 1,1,'') ConcatenatedFROM CTE t1
慕姐8265434
TA贡献1813条经验 获得超2个赞
我想没有GROUP_CONCAT
函数在MSSQL中。
当项目数量较小且预先已知时,收缩值
SELECT CategoryId, MAX( CASE seq WHEN 1 THEN ProductName ELSE '' END ) + ', ' + MAX( CASE seq WHEN 2 THEN ProductName ELSE '' END ) + ', ' + MAX( CASE seq WHEN 3 THEN ProductName ELSE '' END ) + ', ' + MAX( CASE seq WHEN 4 THEN ProductName ELSE '' END ) FROM ( SELECT p1.CategoryId, p1.ProductName, ( SELECT COUNT(*) FROM Northwind.dbo.Products p2 WHERE p2.CategoryId = p1.CategoryId AND p2.ProductName <= p1.ProductName ) FROM Northwind.dbo.Products p1 ) D ( CategoryId, ProductName, seq ) GROUP BY CategoryId ;
- 3 回答
- 0 关注
- 545 浏览
添加回答
举报
0/150
提交
取消