我的订阅表中有两个日期(start_date
和end_date
)。我想了解用户是否在指定月份订阅?例如:start_date=11/20/2011 and end_date=03/10/2012
.我想知道在Feb-2012 (02/2012)
月份订阅的所有用户。
谢谢。
不确定我是否理解,因为其他答案"如此"复杂,但只要您只需要知道 sbdy 是否在一个月内订阅,我就会以简单的方式做到这一点:
SELECT
*
FROM
your_table
WHERE
CONVERT(datetime,'2012-02-01')
between DATEADD(month, DATEDIFF(month, 0, start_date), 0)
and DATEADD(month, DATEDIFF(month, 0, end_date), 0)
只要记住在转换函数中放置一个月的第一天。
像这样的东西?
DECLARE @subscriptionStart datetime;
DECLARE @subscriptionEnd datetime;
DECLARE @monthStart datetime;
DECLARE @monthEnd datetime;
SET @subscriptionStart = '20111120';
SET @subscriptionEnd = '20120310';
SET @monthStart = '20120201';
SET @monthEnd = (dateadd(day,-1* day(dateadd(month,1,@monthStart)),dateadd(month,1,@monthStart)));
SELECT CASE
WHEN @subscriptionStart <= @monthStart
AND @subscriptionEnd >= @monthEnd
THEN 'month between dates'
ELSE 'month not between dates' END AS result
鉴于您以字符串形式传递201202作为感兴趣的月份。
Declare @StartOfMonth DateTime
Declare @EndOfMonth DateTime
Set @StartOfMonth = Convert(DateTime,@MyMonth + '01')
Set @EndOfMonth = DateSubtract(day, 1,DateAdd(month, 1, @StartOfMonth))
这取决于您是否对整个月或该月任何部分订阅的内容感兴趣。
这将使您获得整个月的内容
Select * From Subscriptions Where
StartDate <= @StartOfMonth and EndDate >= @EndOfMonth
或者这会让你在本月的任何时间得到那些
Select * From Subsciptions Where
(@StartOfMonth Between StartDate and EndDate)
Or
(@EndOfMonth Between StartDate and EndDate)
反正就是这样的事情。
试试这个
SET @SpecifiedDate = '2012/02/01'
SELECT * FROM myTable WHERE Start_Date >= @SpecifiedDate
或
WHERE Month(@SpecifiedDate) = MONTH(Start_Date) AND YEAR(@SpecifiedDate) = YEAR(Start_Date)
你可以使用这个
WHERE Month(@SpecifiedDate) >= MONTH(Start_Date) AND Month(@SpecifiedDate) <= MONTH(End_Date)
但我更喜欢使用完整日期(以年、月和 01 为日)。因此,我不会担心这一年,因为SQL将处理过滤
WHERE @SpecifiedDate >= Start_Date AND @SpecifiedDate <= End_Date