2011-03-02 57 views
1

假設我有一個表叫Jobs如何寫一個SQL查詢來呈現值水平

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中執行此操作?

+5

這聽起來好像這是你應該在被處理表示層,不試圖強制通過TSQL – 2011-03-02 06:52:30

+0

@Marc:有很多情況下,表示層不夠靈活,無法處理;您可能需要將此查詢放入視圖,Excel電子表格或報告引擎中。 – Gabe 2011-03-15 06:13:58

回答

3

Marc是對的。不要在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;