微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。