2017-06-21 31 views
-2

我有數據如下如何在不同的列

enter image description here

計算當月和上月值,我需要得到輸出 基本上它說明了什麼是對當前當月計劃(值)月和上個月。 enter image description here

例如: 在[May16] 201605什麼計劃201605作爲價值 和Wat在201604計劃201605上個月[浪美]值

我試着用全外通過連接查詢如果一個月值缺失,則不返回正確的結果

回答

0
select * from table where created_month = (select max(created_month) from table); 
+0

我必須表明所有個月,當月計劃值和上月計劃value..not最新記錄 –

+0

不是那麼清楚你問 – Frank

+0

基本上它的規劃創建月 - 當月週期 - 在幾個月內即將規劃數據。價值 - 預期的結果。因此,我需要在201605年,即可能2016 2016年計劃201605作爲當前月份和笏計劃在201604年201605作爲最後一個月的價值 –

0

您只需通過Created_Month和Period加入同一個表。

drop table if exists dbo.tMonth; 

create table dbo.tMonth (
    Created_Month varchar(100) 
    , Period varchar(100) 
    , Value int 
); 

insert into dbo.tMonth (Created_Month, Period, Value) 
values ('201604', '201604', 1641) 
    , ('201604', '201605', 2458) 
    , ('201605', '201604', 6772) 
    , ('201605', '201605', 9861); 


with cteMonth as (
    select 
     convert(date, m.Created_Month + '01', 112) as Created_Month_Date 
     , * 
    from dbo.tMonth m 
) 
select 
    cm.Created_Month, cm.Period, cm.Value, cmp.Value as LM 
from cteMonth cm 
    left join cteMonth cmP on cm.Created_Month_Date = dateadd(month, 1, cmp.Created_Month_Date) 
      and cm.Period = cmP.Period 
order by cm.Created_Month, cm.Period 
相關問題