[英]Effective SQL Query to find a given month is in between two dates
我的訂閱表中有兩個日期( start_date
和end_date
)。 我想了解用戶是否在指定月份訂閱? 例如: start_date=11/20/2011 and end_date=03/10/2012
。 我想知道Feb-2012 (02/2012)
月份中已訂閱的所有用戶。
謝謝。
假設您將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)
好吧,無論如何。
像這樣嗎
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
不知道我是否理解,因為其他答案太“復雜”了,但是只要您只需要知道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)
只需記住將每月的第一天放在CONVERT函數中即可。
嘗試這個
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.