假设我有一个名为Jobs
的表:
CREATE TABLE [Jobs]
(
[JOBID] [int] IDENTITY(1,1) NOT NULL,
[PARTDESC] [nvarchar](64) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[OrderPlacedBy] [nvarchar](64) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[SpecialistName] [nvarchar](64) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Priority] [int] NOT NULL,
[Symptoms] [ntext] COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[CustomerNotes] [ntext] COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[ShopNotes] [ntext] COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[JobType] [nvarchar](32) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[JobState] [nvarchar](32) COLLATE Latin1_General_CI_AS NULL,
[JobAddedDate] [datetime] NOT NULL,
[JobStartedDate] [datetime] NULL,
[JobFinishedDate] [datetime] NULL,
[JobShippedDate] [datetime] NULL,
[RecievedDate] [datetime] NULL
)
我想横向查看专家姓名及其工作ID。
ANA 201,502,605,701,774
BEN 102,103,051
JEN 705,401,402,509,409,408
专科医生可能有n
个工作。假设专家ANA
有10个工作岗位,其中BEN有5个工作岗位。
通过这种方式,我想向专家展示他的工作水平,其中每个专业人员的工作数量可能会有所不同。
如何在SQL中执行此操作?
答案 0 :(得分:3)
根据您的情况,代码可能是:
select SpecialistName , LEFT(JobsIds, len(JobsIds)-1) as JobsIds from
(SELECT j.SpecialistName ,
( SELECT cast(j1.JobsId as varchar(10)) + ','
FROM Jobs j1
WHERE j1.SpecialistName = j.SpecialistName
ORDER BY JobId
FOR XML PATH('') ) AS JobsIds
FROM Jobs j
GROUP BY SpecialistName )A;