将不存在的个案声明用作Where子句的一部分

时间:2019-04-11 22:52:44

标签: sql-server

我正在计算车辆的折旧,如果存在,则需要获取前一个月的值。

我在where子句中编写了一个case语句,以查看该值是否存在。如果是这样,那么我想减去一个月并使用该值来获取前几个月的数据。如果不存在,则需要当前月份的数据。但是它只会做一个或另一个。我会搞砸存在的地方吗?

SELECT b.*
--this is month we want to compare (For example month 45)
FROM #changes AS a 
--this has all the months  (for example month 1-50)
INNER JOIN work.dbo.DepreciationSchedule AS b 
    ON b.VehicleID = a.VehicleID
--If the previous months value exists in table b (Ex month 44), then take take that months value otherwise take the current value of table a (Ex month 45)
WHERE b.Month = CASE 
                    WHEN EXISTS(SELECT * 
                                 FROM #changes AS innerA 
                                 WHERE innerA.month = a.month - 1) 
                    THEN a.Month - 1  
                    ELSE a.Month 
                END

1 个答案:

答案 0 :(得分:0)

我知道了。我必须改变两件事。

  1. 将车辆ID添加到当前子查询中,以确保我只希望临时表中有这些车辆。
  2. 将子查询表更改为折旧时间表

    选择b。*     -这是我们要比较的月份(例如,第45个月)     来自#changes作为     -这具有所有月份(例如1-50个月)     内连接work.dbo.DepreciationSchedule as b     在b.VehicleID = a.VehicleID上     -如果表b中存在前一个月份的值(例如,月份44),则取该月份的值,否则取表a的当前值(例如,月份45)     其中b.Month =存在的情况(选择* From work.dbo.DepreciationSchedule作为innerA,其中innerA.month = a.month-1和innerA.VehicleID = a.vehicleID)然后a.Month -1否则a.Month end < / p>