有没有办法让我的失踪月份恢复SQL

时间:2019-01-09 03:22:53

标签: sql

我的搜索结果缺少一月份,因为我的代码要求year = year。如何在此搜索中获得一月份的结果

我尝试将datepart和没有datepart添加到month_end_date = month_end_date

SELECT f.id
    ,f.bus#
    ,f.Mileage
    ,f.month_end_date
    ,f.Year
    ,f.Month
    ,f.Mileage - ISNULL(f2.Mileage, 0) AS diff
FROM dbo.NEWMILEAGEVIEW AS f
LEFT OUTER JOIN dbo.NEWMILEAGEVIEW AS f2 ON f2.bus# = f.bus#
WHERE (f.bus# = f2.bus#)
    AND (DATEPART(m, f.month_end_date) = DATEPART(m, f2.month_end_date) + 1)
    AND (f.Year = f2.Year)

搜索应该将此行带回01-01-13

id  month_end_date  month_start Bus Mileage fleet   Month   Year    bus#
92  2012-11-30  2012-12-01  Bus1801 33500   18462010    11  2012    1801
93  2012-12-31  2013-01-01  Bus1801 35480   18628718    12  2012    1801 

但是它跳过了01-01-13,因为年份不同

id  bus#    Mileage month_end_date  Year    Month   diff
93  1801    35480   2012-12-31  2012    12  1980
95  1801    39436   2013-02-28  2013    2   2208

2 个答案:

答案 0 :(得分:1)

在这种情况下,我会使用datediff()

SELECT . . .
FROM dbo.NEWMILEAGEVIEW f LEFT OUTER JOIN
     dbo.NEWMILEAGEVIEW f2
     ON f2.bus# = f.bus# AND
        DATEDIFF(month, f2.month_end_date, f.month_end_date) = 1

但是,LAG()是更好的解决方案:

SELECT . . .,
       (f.Mileage -
        LAG(f2.Mileage, 1, 0) OVER (PARTITION BY bus# ORDER BY month_end_date)
       ) as diff
FROM dbo.NEWMILEAGEVIEW f 

答案 1 :(得分:0)

如果有一些示例数据,这将有所帮助,但是基本上您的左联接就像内部联接,并且仅返回匹配的记录(如您在where条件中添加的记录)。为了避免这种情况,您可以通过这种方式使用。

SELECT f.id
,f.bus#
,f.Mileage
,f.month_end_date
,f.Year
,f.Month
,f.Mileage - ISNULL(f2.Mileage, 0) AS diff
FROM dbo.NEWMILEAGEVIEW AS f
LEFT OUTER JOIN dbo.NEWMILEAGEVIEW AS f2 ON f2.bus# = f.bus#
AND (DATEPART(m, f.month_end_date) = DATEPART(m, f2.month_end_date) + 1)
AND (f.Year = f2.Year)