SQL返回同一年的最后30条记录

问题描述

在我的查询中,我只想返回同一年内最近30天中保存的记录,但是我的查询返回从今天的月份和日期开始的所有30天中发生的所有记录,而与年份无关。我不知道是什么原因 我在较小的查询中尝试了该条件,并给出了正确的结果。

select top 10000 
      cb.billNo,MAX(cb.subCategoryID) subCategory,Max(cb.cateogryID) categoryID,MAX(tracking.date ) trackingDate,Max(Station.Code) Dest,Max(cb.picesCount) PieceCount,Max(case when cb.productCount > 1 then 1 else 0 end) isMultiProduct,Max(case when tt.ID = 1 and (cb. subCategoryID = 65 or cb. 
      subCategoryID 
      = 56) then 1 else 0 end) isReceived,from CustomerBillss cb
     join Tracking on cw.billNo = Tracking.billNo
     join trackingtype tt on Tracking.TrackingTypeID = tt.ID
     join Station on cb.destinationStationID = Station.ID

where 
tracking.date > dateadd(dd,-30,cast(getdate() as date))
--(YEAR(tracking.Date) = YEAR(GETDATE()) AND
--tracking.Date >= DATEADD(day,GETDATE()))
AND
cb. cateogryID in (1,3)
AND Tracking.TrackingTypeID not in (8,4,20) 
AND cb.subCategoryID != 30 or (
   subCategoryID = 30 and cb.DestinationStationID = tracking.StationID)
group by cb.billNo;

解决方法

只需取消注释所选的年份过滤器

select top 10000 
          cb.billNo,MAX(cb.subCategoryID) subCategory,Max(cb.cateogryID) categoryID,MAX(tracking.date ) trackingDate,Max(Station.Code) Dest,Max(cb.picesCount) PieceCount,Max(case when cb.productCount > 1 then 1 else 0 end) isMultiProduct,Max(case when tt.ID = 1 and (cb. subCategoryID = 65 or cb. 
          subCategoryID 
          = 56) then 1 else 0 end) isReceived,from CustomerBillss cb
         join Tracking on cw.billNo = Tracking.billNo
         join trackingtype tt on Tracking.TrackingTypeID = tt.ID
         join Station on cb.destinationStationID = Station.ID
    
    where 
    tracking.date > dateadd(dd,-30,cast(getdate() as date))
    (YEAR(tracking.Date) = YEAR(GETDATE()) AND
    --tracking.Date >= DATEADD(day,GETDATE()))
    AND
    cb. cateogryID in (1,3)
    AND Tracking.TrackingTypeID not in (8,4,20) 
    AND cb.subCategoryID != 30 or (
       subCategoryID = 30 and cb.DestinationStationID = tracking.StationID)
    group by cb.billNo;