I have two dates in my subscription table ( start_date
and end_date
). I want to find out if the user is subscribed in the specified month or not? For ex: start_date=11/20/2011 and end_date=03/10/2012
. I want to know all users who are subscribed in the month of Feb-2012 (02/2012)
.
Thank you.
Given you pass in 201202 as the month of interest as a string.
Declare @StartOfMonth DateTime
Declare @EndOfMonth DateTime
Set @StartOfMonth = Convert(DateTime,@MyMonth + '01')
Set @EndOfMonth = DateSubtract(day, 1,DateAdd(month, 1, @StartOfMonth))
The it depends on whether you are interested in those subscribed for the whole month or any part of the month.
This will get you those for the whole month
Select * From Subscriptions Where
StartDate <= @StartOfMonth and EndDate >= @EndOfMonth
Or this will get you those for any part of the month
Select * From Subsciptions Where
(@StartOfMonth Between StartDate and EndDate)
Or
(@EndOfMonth Between StartDate and EndDate)
Well something like that anyway.
Something like this?
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
Not sure if I understand, because other answers are "so" complicated, but as long as you only need to know if sbdy is subscribed within a month I would do this in a simple way:
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)
Just remember to put a first day of month within CONVERT function.
Try this
SET @SpecifiedDate = '2012/02/01'
SELECT * FROM myTable WHERE Start_Date >= @SpecifiedDate
OR
WHERE Month(@SpecifiedDate) = MONTH(Start_Date) AND YEAR(@SpecifiedDate) = YEAR(Start_Date)
You can use this
WHERE Month(@SpecifiedDate) >= MONTH(Start_Date) AND Month(@SpecifiedDate) <= MONTH(End_Date)
But I prefer using the the full date (with the year, month and 01 as day). Thus I won't worry about the year since SQL will handle the filtering
WHERE @SpecifiedDate >= Start_Date AND @SpecifiedDate <= End_Date
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.