1

我有一个存储过程,如下所示:

ALTER PROC [dbo].[USP_GetDraftQuoteByQuoteID]
(@QuoteID int)
AS 
BEGIN
SELECT cl.Quote_ID,cl.PECCode,lpu.Description,cl.Site_ID,cl.Quantity
FROM ConfigurationList cl
LEFT OUTER JOIN LPU lpu
ON cl.PECCode=lpu.PECCode
WHERE Quote_ID = @QuoteID

我得到如下所示的输出:

Quote   PECCode      Description  Site ID    Quantity
9   NTK539PDE5       OCLD            IND        8
9   NTK525FAE5       NULL            BVT        4
9   NTK531YAE5       NULL            CAX        3
9   NTNM34TB         NULL            IND        5
9   NTK569HA         NULL            COX        8
9   NTNM70ER         NULL            CBA        4
9   CNMT278BR        NULL            IND        4
9   NTRU0411         NULL            BVT        8

但我想得到如下输出:

Quote   PECCode      Description  IND   BVT   CAX   COX   CBA
9   NTK539PDE5       OCLD           8
9   NTK525FAE5       NULL                4
9   NTK531YAE5       NULL                      3
9   NTNM34TB         NULL           5                  
9   NTK569HA         NULL                             8      
9   NTNM70ER         NULL                                   4
9   CNMT278BR        NULL           4      
9   NTRU0411         NULL               8

此处,数量基于 PECCode 和站点。我认为在这里我们必须使用 PIVOT 概念。但是我将无法达到预期的结果。任何人请帮忙。

4

1 回答 1

1

尝试这个:

SELECT QuoteID, PECCode, Desc, 
[IND] as IND_Site, [BVT] as BVT_Site, [CAX] as CAX_Site, [COX] as COX_Site, [CBA] as CBA_Site
FROM
(

SELECT cl.Quote_ID AS QuoteID
,cl.PECCode as PECCode
,lpu.Description as Desc
,cl.Site_ID as SiteID
,cl.Quantity as Quant
FROM ConfigurationList cl
LEFT OUTER JOIN LPU lpu
ON cl.PECCode=lpu.PECCode
WHERE Quote_ID = @QuoteID) T

PIVOT

(
   SUM (Quant)
   FOR
      SiteID IN ([IND], [BVT], [CAX], [COX], [CBA])
) as Pivoted_Table
ORDER BY PECCode
于 2013-06-13T10:56:44.090 回答