使用自联接和case语句创建视图

时间:2013-12-20 20:29:14

标签: sql-server-2008

Sql Server 2008 R2 我有这些数据: Id AdOrderId AdRunScheduleId CategoryCode EffectiveDate Amount
735935 3811 1629 0 3/7/14 0:00 72.19
735939 3811 1629 2 3/7/14 0:00 10
 735942 3811 1629 7 3/7/14 0:00 -14.44

我想要一个包含所有3条记录的1行的视图 我尝试过几件事。几项工作但都给了我3行。

这是我最近的尝试:

    -CREATE View [dbo].[DP_AdOrder_Charges]
    --as
    SELECT
    Elem.Id,
    Elem.AdOrderId, Elem.AdRunScheduleId, Elem.EffectiveDate, 
    Elem.Amount, Elem.CategoryCode,
    MAX(Case when Elem.CategoryCode = 0  then Elem.Amount End) as AdInsertAmt,
    MAX(Case when Elem.CategoryCode = 2  then Elem.Amount End) as ColorAmt,
    MAX(Case when Elem.CategoryCode = 7  then Elem.Amount End) as DiscAmt,
    MAX(Case when Elem.CategoryCode not in (0,2,7) then Elem.Amount End) as OtherAmt
          FROM [MNADTEST].[dbo].[RtChargeEntryElem] Elem
    INNER JOIN [MNADTEST].[dbo].[RtChargeEntryElem] J1
    ON Elem.EffectiveDate=J1.EffectiveDate
    and Elem.Id=J1.Id
    and Elem.AdRunScheduleId=J1.AdRunScheduleId
    and Elem.AdOrderId=J1.AdOrderId
    Where Elem.AdRunScheduleId=1629
      and Elem.EffectiveDate='2014-03-07'
    GROUP BY
    Elem.Id,Elem.EffectiveDate,
    Elem.AdOrderId, Elem.AdRunScheduleId, 
    Elem.Amount, Elem.RateTableId, Elem.CategoryCode

with this result


    Id  AdOrderId   AdRun   Effective   Amount  Category    AdInsertAmt ColorAmt   DiscAmt  OtherAmt
            ScheduleId  Date            Code        
735935  3811        1629    2014-03-07    72.19 0      72.19    NULL       NULL     NULL
735939  3811        1629    2014-03-07    10    2      NULL     10     NULL     NULL
735942  3811        1629    2014-03-07    -14.44    7      NULL     NULL       -14.44   NULL

I would be grateful for any help.
thanks.
Barb

这是创建表和插入代码:

    CREATE TABLE [dbo].[RtChg](
    [Id] [int] NOT NULL,
    [AdOrderId] [int] NULL,
    [AdRunScheduleId] [int] NULL,
    [CategoryCode] [int] NULL,
    [EffectiveDate] [datetime] NULL,
    [Amount] [float] NULL   
    )
GO

INSERT INTO [dbo].[RtChg]
    ([Id],
    [AdOrderId],
    [AdRunScheduleId],
    [CategoryCode],
    [EffectiveDate],
    [Amount])
VALUES
    (735935, 3811, 1629, 0, '3/7/14', '72.19'),
    (735939 ,3811, 1629, 2, '3/7/14', '10.00'),
    (735942, 3811, 1629, 7, '3/7/14', '-14.44')
GO 

1 个答案:

答案 0 :(得分:0)

我有这个工作。我不需要自我加入。此外,我正在使用唯一ID进行分组,而不是在值更改时要捕获的列。

CREATE View [dbo].[DP_AdOrder_Charges]
as
SELECT
AdOrderId,
Elem.AdRunScheduleId, 
Elem.EffectiveDate, 
MAX(Case when Elem.CategoryCode = 0  then Elem.Amount End) as AdInsertAmt,
MAX(Case when Elem.CategoryCode = 2  then Elem.Amount End) as ColorAmt,
MAX(Case when Elem.CategoryCode = 7  then Elem.Amount End) as DiscAmt,
MAX(Case when Elem.CategoryCode not in (0,2,7) then Elem.Amount End) as OtherAmt
      FROM [MNADTEST].[dbo].[RtChargeEntryElem] Elem
GROUP BY
Elem.AdOrderId,
Elem.AdRunScheduleId, 
Elem.EffectiveDate