简体   繁体   English

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

[英]SQL return last 30 records on the same year

In my query I want to return only the records that saved in last 30 days within same year but my query returns all the records that happened in last 30 days from today's month and day regardless of the year.在我的查询中,我只想返回同一年内过去 30 天内保存的记录,但我的查询返回从今天的月份和日期开始的过去 30 天内发生的所有记录,而不管年份如何。 I don't know what the reason I tried the condition in smaller query and it gives right result.我不知道我在较小的查询中尝试条件的原因是什么,它给出了正确的结果。

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,-30,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;

Just uncomment the year filter in your select只需在您的选择中取消注释年份过滤器

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,-30,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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM