简体   繁体   中英

Display value from previous month SQL

在此处输入图片说明

Hi, I have columns as above. How to create select that in column "prev value" will display "value" from previous reporting date (previous month)?

select id, name, name2, value, 
(
select value from bi_date as b2 
where b1.month(reporting_date) = (b2.month(reporting_date)-1)
) as prev_value

from table1 as b1
select id, name, name2, value
(
   select value from bi_date
   where DATEPART(m, reporting_date) = DATEPART(m, DATEADD(m, -1, getdate()))
   AND DATEPART(yyyy, reporting_date) = DATEPART(yyyy, DATEADD(m, -1, getdate()))
)

Here you need to check each record month and year. I hope this will be work for you...

Try using DATEADD() and also use a condition on the correlated query to know which id to look for.

select id, name, name2, value, 
(
    select TOP 1 value from bi_date b2 
    where month(b1.reporting_date) = month(DATEADD(month,1,b2.reporting_date))
      AND YEAR(b1.reporting_date) = YEAR(DATEADD(month,1,b2.reporting_date))
      AND b1.id = b2.id
) as prev_value
from table1 as b1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM