Suppose I have one table called 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_Ge开发者_如何学运维neral_CI_AS NULL,
[JobAddedDate] [datetime] NOT NULL,
[JobStartedDate] [datetime] NULL,
[JobFinishedDate] [datetime] NULL,
[JobShippedDate] [datetime] NULL,
[RecievedDate] [datetime] NULL
)
I want to see the specialist name and his jobs IDs horizontally.
ANA 201,502,605,701,774
BEN 102,103,051
JEN 705,401,402,509,409,408
A specialist may have n
jobs. Suppose specialist ANA
has 10 jobs where BEN has 5 jobs.
In this way I want to show specialist his jobs horizontally where the number of jobs may vary per specialist.
How can I do this in SQL?
Marc is right. Don't do this in SQL, do it at the presentation level. Still, if you want to do this, take a look here: How to return 1 single row data from 2 different tables with dynamic contents in sql
Applied to your situation, the code might be:
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;
精彩评论