显示上个月SQL的值

时间:2016-03-07 15:18:38

标签: sql sql-server date subquery vlookup

enter image description here

您好, 我上面有专栏。如何创建选择列" prev值"将显示"值"从上一个报告日期(上个月)?

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

2 个答案:

答案 0 :(得分:1)

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()))
)

在这里,您需要检查每个记录月份和年份。我希望这对你有用......

答案 1 :(得分:0)

尝试使用DATEADD()并在相关查询上使用条件来了解要查找的ID。

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