如何在sqlserver中用commasepart实现行到列的转换

uyto3xhc  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(349)

我有一个关于SQLServer的问题:如何使用批量数据将带有逗号分隔数据的行转换为列?

CREATE TABLE [dbo].[Emp]
(
    [eid] [int] NULL,
    [name] [varchar](50) NULL,
    [sal] [money] NULL,
    [doj] [date] NULL,
    [deptno] [int] NULL
) 

INSERT [dbo].[Emp] ([eid], [name], [sal], [doj], [deptno]) 
VALUES (1, N'a', 100.0000, CAST(N'2010-10-01' AS Date), 10)

INSERT [dbo].[Emp] ([eid], [name], [sal], [doj], [deptno]) 
VALUES (2, N'bb', 200.0000, CAST(N'2010-02-03' AS Date), 20)

INSERT [dbo].[Emp] ([eid], [name], [sal], [doj], [deptno]) 
VALUES (3, N'c', 300.0000, CAST(N'2017-02-03' AS Date), 30)

INSERT [dbo].[Emp] ([eid], [name], [sal], [doj], [deptno]) 
VALUES (4, N'd', 301.0000, CAST(N'2010-03-04' AS Date), 10)

INSERT [dbo].[Emp] ([eid], [name], [sal], [doj], [deptno]) 
VALUES (5, N'teee', 250.0000, CAST(N'2010-06-04' AS Date), 20)

INSERT [dbo].[Emp] ([eid], [name], [sal], [doj], [deptno]) 
VALUES (7, N'tte', 800.0000, CAST(N'2010-08-09' AS Date), 70)

我希望输出如下:

userlist
1,2,3,4,5,7

我试过这个代码:

select distinct  
    stuff((select ',' + cast(u.eid as varchar)
           from emp u
           where 1 = 1
           for xml path('')), 1, 1, '') as userlist
from emp

假设数据有10万个条目,那么这个查询不会返回10万个逗号分隔的条目
您能告诉我如何在SQLServer中编写查询来完成这个任务吗?

tuwxkamq

tuwxkamq1#

我认为查询工作如预期。但结果太大,无法在managementstudio中显示。

相关问题