如何编写SQL查询以水平呈现值

时间:2011-03-02 06:49:09

标签: sql sql-server-2005

假设我有一个名为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中执行此操作?

1 个答案:

答案 0 :(得分:3)

马克是对的。不要在SQL中执行此操作,请在演示级别执行此操作。 不过,如果你想这样做,请看一下: How to return 1 single row data from 2 different tables with dynamic contents in sql

根据您的情况,代码可能是:

     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;