2016-11-09 31 views
0

* UPDATE獲得的最近3個月創紀錄的具體數值不重複

我試着去得到已付金額爲記錄的前3個月有,無論組件的相同的分類。

  • 我試過新的代碼,它給了我想要的輸出,但是對於每個組件來說,該值仍然是重複的。

這是在數據庫中的樣本記錄:

enter image description here

,這是我到目前爲止已經試過代碼*新代碼:

SELECT * 
    INTO #Q1 
    FROM TenantRecord 

    --GET Previous MONTH 
    SELECT * 
    INTO #Q2 
    FROM TenantRecord 
    where Date between @PREVMonthStart and @PREVMonthEnd 

    --GET Previous 2nd MONTH 
    SELECT * 
    INTO #Q3 
    FROM TenantRecord 
    where Date between @PREV2ndMonthStart and @PREV2ndMonthEnd 

    --GET Previous 3rd MONTH 
    SELECT * 
    INTO #Q4 
    FROM TenantRecord 
    where Date between @PREV3rdMonthStart and @PREV3rdMonthEnd 

    select a.Tenant, a.Classification, a.Date, a.Component, a.AmountP, 
    (case when b.Classification != a.Classification then null else b.AmountP end) as Previous1, 
    (case when c.Classification != a.Classification then null else c.AmountP end) as Previous2, 
    (case when d.Classification != a.Classification then null else d.AmountP end) as Previous3 
    from #Q1 a 
    LEFT JOIN #Q2 b on a.Tenant = b.Tenant 
    LEFT JOIN #Q3 c on a.Tenant = c. Tenant 
    LEFT JOIN #Q4 d on a.Tenant = d.Tenant 

    where date between @CurrentMonthStart and @CurrentMonthEnd 

這是輸出代碼:

enter image description here

但我想要的輸出是這樣的:

![enter image description here

回答

0

請仔細閱讀此可能的解決方案:

Declare @currentDate date = '2016-07-30'; 
With cte As (
    Select Tenant, Classification, Component, Month([Date]) As [Month], Amount 
     From #TenantRecord 
     Where Year([Date]) >= Year(DateAdd(Month, -4, @currentDate)) 
     And Month([Date]) >= Month(DateAdd(Month, -4, @currentDate))) 
Select Tenant, Classification, Component, July = [7], June = [6], May = [5], April = [4] 
    From cte 
    Pivot (Sum(Amount) For [Month] In ([4], [5], [6], [7])) As pvt; 

我是否是我用過的語言元素有點朦朧遵守ISO標準SQL,並且您還沒有指定RDBMS。這應該適用於Microsoft

編輯:

Declare @currentDate date = '2016-07-30'; 
With cte As (
    Select Tenant, Classification, AmountPaid, 
     Month(@currentDate) - Month([Date]) As [MonthsAgo] 
     From #TenantRecord 
     Where Year([Date]) >= Year(DateAdd(Month, -4, @currentDate)) 
     And Month([Date]) >= Month(DateAdd(Month, -4, @currentDate))), 
PivotByTenantClassification As (
    Select Tenant, Classification, [0], [1], [2], [3] 
     From cte 
     Pivot (Sum(AmountPaid) For [MonthsAgo] In ([0], [1], [2], [3])) As pvt) 
Select t.Tenant, t.Classification, t.Date, t.Component, [0], [1], [2], [3] 
    From #TenantRecord As t 
    Join PivotByTenantClassification As pvt 
    On t.Tenant = pvt.Tenant 
    And t.Classification = pvt.Classification 
    Where Year([Date]) = Year(@currentDate) 
    And Month([Date]) = Month(@currentDate); 
+0

謝謝您的回答,但我想要的是讓所有的價值,而不是總的最後3個月,就像在第三照片。 – KevinNEWBIE

+0

@KevinNEWBIE這樣做有點複雜,並且有點奇怪,當前月份中每個分類支付的金額都會有一行。見編輯的例子。 – mendosi