如何在SQL Server中获取具有日期的行少于30天?

时间:2014-10-21 10:24:05

标签: sql-server

我有以下表结构:

表:tbl_CustomerPromos

COLUMN       DATATYPE
PromoCodeID  int (IDENTITY)
CustomerID   int
PromoCode    nvarchar(50)
AddedDate    DateTime
IsPromoUsed  smallint

我想向所有客户发送电子邮件通知从加入之日(AddedDate)到接下来的30天之后的每7天。

select 
   pc.[CustomerID]
   , pc.[PromoCode]
   , pc.[DiscountAmount]
   , ISNULL(pc.[IsPromoUsed], 0) IsPromoUsed
   , pc.[AddedBy]
   , pc.[AddedDate]
   , (c.FirstName + ' ' + c.LastName) FullName
   , c.Email
from 
   tbl_PromoCodesNewCustomer pc
Left join 
   tbl_Customers c on pc.CustomerID = c.CustomerID
Where 
   isnull(pc.IsPromoUsed, 0) <> 1
   AND pc.AddedDate = ?

注意:从加入(AddedDate)到接下来的30天,而不是加入月份,计算30天。

那么,如何获取日期少于30天的行(AddedDate从今天起不超过30天)

3 个答案:

答案 0 :(得分:1)

尝试lyk this

select ..
from table
where datediff(dd,AddedDate,getdate())<30 and ..

答案 1 :(得分:1)

要获得'每7天'过滤器,我建议你MODULO日期差异(在30天内检查它之后)。 CTE将帮助干预这一点。另外,我假设你每天只运行一次。

WITH EligiblePromoCodes AS
(
   SELECT 
      CustomerId,
      PromoCode,
      IsPromoUsed,
      DiscountAmount,
      AddedDate,
      AddedBy,
      DATEDIFF(dd, AddedDate, CURRENT_TIMESTAMP) AS DaysSinceAdded
   FROM
     tbl_PromoCodesNewCustomer
)
SELECT
   pc.[CustomerID]
   , pc.[PromoCode]
   , pc.[DiscountAmount]
   , ISNULL(pc.[IsPromoUsed], 0) IsPromoUsed
   , pc.[AddedBy]
   , pc.[AddedDate]
   , (c.FirstName + ' ' + c.LastName) FullName
   , c.Email
from 
   EligiblePromoCodes pc
Left join 
   tbl_Customers c on pc.CustomerID = c.CustomerID
Where 
   isnull(pc.IsPromoUsed, 0) <> 1
   AND DaysSinceAdded <= 30 
   AND DaysSinceAdded % 7 = 0;

SqlFiddle here

答案 2 :(得分:0)

select pc.[CustomerID]
    ,pc.[PromoCode]
    ,pc.[DiscountAmount]
    ,isnull(pc.[IsPromoUsed],0)IsPromoUsed
    ,pc.[AddedBy]
    ,pc.[AddedDate]
    ,(c.FirstName +' '+ c.LastName)FullName
    ,c.Email
from tbl_PromoCodesNewCustomer pc
Left join tbl_Customers c
on pc.CustomerID=c.CustomerID
Where isnull(pc.IsPromoUsed,0)<>1
AND datediff(dd,pc.AddedDate,getdate())<30 order by pc.AddedDate desc