Looking for a birthdate Range in SQL - sql

I am looking for a birthdate range of march 21 to April 20, and the year doesn't matter. and it seems that when i search other months and date are coming out.
select * from AllStudentInfo Where
((MONTH(birthDate) >= 3 and day(birthDate) >= 21)
OR
(MONTH(birthDate) <= 4 and day(birthDate) <= 20))
AND
(BGRStatus = 'S' OR BGRStatus = 'SL')

Chances are that you want to discover up & coming dates. In any case, you can create a virtual date as follows:
SELECT DATEFROMPARTS (2017,month(birthDate),day(birthDate) as birthday
FROM AllStudentInfo
In this case, you can use:
SELECT *
FROM AllStudentInfo
WHERE DATEFROMPARTS (2017,month(birthDate),day(birthDate)
BETWEEN '2017-03-21' AND '2017-04-20';
The year 2017 is arbitrary. The point is that the dates in the BETWEEN clause are in the same year.
Using more modern techniques, you can combine it as follows:
WITH cte AS(
SELECT *,DATEFROMPARTS (2017,month(birthDate),day(birthDate) as birthDay
FROM AllStudentInfo
)
SELECT * FROM cte WHERE birthDay BETWEEN '2017-03-21' AND '2017-04-20';
The cte is a Common Table Expression which is an alternative to using a sub query.
Here is an alternative which is closer to the spirit of the question. You can use the format function to generate an expression which is purely month & day:
format(birthDate,'MM-dd')
The MM is MSSQL’s way of saying the 2-digit month number, and dd is the 2-digit day of the month.
This way you can use:
format(birthDate,'MM-dd') BETWEEN '03-21' AND '04-20'
Again as a CTE:
WITH cte AS(
SELECT *,format(birthDate,'MM-dd') as birthDay
FROM AllStudentInfo
)
SELECT * FROM cte WHERE birthDay BETWEEN '03-21' AND '04-20';
You should get the same results, but the year is completely ignored.

Switch your statement to AND
Like so
select * from AllStudentInfo Where
((MONTH(birthDate) >= 3 and day(birthDate) >= 21)
AND --Make the change here
(MONTH(birthDate) <= 4 and day(birthDate) <= 20))
AND
(BGRStatus = 'S' OR BGRStatus = 'SL')
Using OR you are querying anything that is in that date range OR that month range. And therefore, you would get results from other every months.

Related

How to compare date (month/year) with another date (month/year)

How to compare parts of date in Informix DBMS:
I wrote the following query but I get a syntax error:
select id,name from h_history
where ( h_date::DATETIME YEAR TO MONTH >= 2/2012 )
and ( h_date::DATETIME YEAR TO MONTH <= 1/2013 )
I wanna to compare with year and month
How to do this?
If you're going to use the DATETIME route, you need to format the values correctly. As it is, you've written:
select id,name from h_history
where ( h_date::DATETIME YEAR TO MONTH >= 2/2012 )
and ( h_date::DATETIME YEAR TO MONTH <= 1/2013 )
The 2/2012 is an integer division equivalent to 0, and there's no implicit cast from integers to datetime or vice versa.
You could write:
-- Query 1
SELECT id, name
FROM h_history
WHERE (h_date::DATETIME YEAR TO MONTH >= DATETIME(2012-02) YEAR TO MONTH)
AND (h_date::DATETIME YEAR TO MONTH <= DATETIME(2013-01) YEAR TO MONTH)
That's verbose but precise. You could use a short-cut:
-- Query 2
SELECT id, name
FROM h_history
WHERE (h_date::DATETIME YEAR TO MONTH >= '2012-02')
AND (h_date::DATETIME YEAR TO MONTH <= '2013-01')
However, since h_date is a DATE rather than a DATETIME X TO Y type, there are other options available. The YEAR, MONTH, DAY functions extract the obvious parts from a DATE (and, if you pass a DATETIME to the function, then the DATETIME will be coerced into a DATE and then processed). The only fully locale-independent DATE constructor is the MDY function which takes 3 arguments, the month, day and year. All string representations are subject to interpretation by locale, and therefore won't work everywhere all the time.
You can also do:
-- Query 3
SELECT id, name
FROM h_history
WHERE (h_date >= MDY(2, 1, 2012))
AND (h_date <= MDY(1, 31, 2013))
Or:
-- Query 4
SELECT id, name
FROM h_history
WHERE ((YEAR(h_date) = 2012 AND MONTH(h_date) >= 2) OR YEAR(h_date) >= 2013)
AND ((YEAR(h_date) = 2013 AND MONTH(h_date) <= 1) OR YEAR(h_date) < 2013)
Or:
-- Query 5
SELECT id, name
FROM h_history
WHERE (YEAR(h_date) * 100 + MONTH(h_date)) >= 201202
AND (YEAR(h_date) * 100 + MONTH(h_date)) <= 201301
Given the choice, I'd probably use Query 2 as succinct but accurate, or perhaps Query 5, but all of queries 1-5 are usable.
If h_date was a column of some DATETIME type and you need to compare parts of a DATETIME, you can either use casting (as shown in Query 1) or the EXTEND function. That tends to be verbose.
Assuming that h_date is a proper date field, why wouldn't
SELECT
id
, name
FROM h_history
WHERE h_date >= '02/01/2012' and h_date <= '01/31/2013'
work for you?
Try the following
SELECT
id,name
FROM h_history
WHERE
h_date >= MDY(2, 1, 2012)
AND h_date < MDY(2, 1, 2013)
select * from table t where MONTH(t.date) = 12

In SQL how to return records matching date and month only (ignore year)

Using SQL, I want to return all records where the date is between 1st March and 31st June (for example), but the records should cover all years. Is there a simple way I can achieve this?
Here is what you would do if you are using PL/SQL or oracle SQL+
SELECT * FROM table
WHERE TO_CHAR(MONTH_COLUMN,'MM/DD') = '06/21'
this will give you all the rows that have a date of June 21 regardless of the year.
For SQL Server use:
select *
from table
where month(dtgCol) between 3 and 6
Use the date functions to get the Month and the Day of Month from the date field and use in the where clause.
Depending on your DB, the function names may vary. But it will be in general like
SELECT * FROM table
WHERE Month(dateField) = 6
AND (DayOfMonth(dateField) >= 1 AND DayOfMonth(dateField) <= 30)
in SQL Server:
SELECT * FROM table
WHERE Month(dateField) = 6
AND (Day(dateField) >= 1 AND Day(dateField) <= 30)
Try this, definitely work
SELECT *
FROM Table
WHERE Month(DateColumn) IN (3, 4, 5, 6)
For SQL Server I'll use following.
eg:between 1st March and 31st June
select * from (
select *,DATEFROMPARTS(2011,MONTH(CreateDate),DAY(CreateDate)) as dt from tblAction
) as x
where x.dt between
DATEFROMPARTS(2011,3,1) and
DATEFROMPARTS(2011,6,31)
See if it helps..:)

Return just the last day of each month with SQL

I have a table that contains multiple records for each day of the month, over a number of years. Can someone help me out in writing a query that will only return the last day of each month.
SQL Server (other DBMS will work the same or very similarly):
SELECT
*
FROM
YourTable
WHERE
DateField IN (
SELECT MAX(DateField)
FROM YourTable
GROUP BY MONTH(DateField), YEAR(DateField)
)
An index on DateField is helpful here.
PS: If your DateField contains time values, the above will give you the very last record of every month, not the last day's worth of records. In this case use a method to reduce a datetime to its date value before doing the comparison, for example this one.
The easiest way I could find to identify if a date field in the table is the end of the month, is simply adding one day and checking if that day is 1.
where DAY(DATEADD(day, 1, AsOfDate)) = 1
If you use that as your condition (assuming AsOfDate is the date field you are looking for), then it will only returns records where AsOfDate is the last day of the month.
Use the EOMONTH() function if it's available to you (E.g. SQL Server). It returns the last date in a month given a date.
select distinct
Date
from DateTable
Where Date = EOMONTH(Date)
Or, you can use some date math.
select distinct
Date
from DateTable
where Date = DATEADD(MONTH, DATEDIFF(MONTH, -1, Date)-1, -1)
In SQL Server, this is how I usually get to the last day of the month relative to an arbitrary point in time:
select dateadd(day,-day(dateadd(month,1,current_timestamp)) , dateadd(month,1,current_timestamp) )
In a nutshell:
From your reference point-in-time,
Add 1 month,
Then, from the resulting value, subtract its day-of-the-month in days.
Voila! You've the the last day of the month containing your reference point in time.
Getting the 1st day of the month is simpler:
select dateadd(day,-(day(current_timestamp)-1),current_timestamp)
From your reference point-in-time,
subtract (in days), 1 less than the current day-of-the-month component.
Stripping off/normalizing the extraneous time component is left as an exercise for the reader.
A simple way to get the last day of month is to get the first day of the next month and subtract 1.
This should work on Oracle DB
select distinct last_day(trunc(sysdate - rownum)) dt
from dual
connect by rownum < 430
order by 1
I did the following and it worked out great. I also wanted the Maximum Date for the Current Month. Here is what I my output is. Notice the last date for July which is 24th. I pulled it on 7/24/2017, hence the result
Year Month KPI_Date
2017 4 2017-04-28
2017 5 2017-05-31
2017 6 2017-06-30
2017 7 2017-07-24
SELECT B.Year ,
B.Month ,
MAX(DateField) KPI_Date
FROM Table A
INNER JOIN ( SELECT DISTINCT
YEAR(EOMONTH(DateField)) year ,
MONTH(EOMONTH(DateField)) month
FROM Table
) B ON YEAR(A.DateField) = B.year
AND MONTH(A.DateField) = B.Month
GROUP BY B.Year ,
B.Month
SELECT * FROM YourTableName WHERE anyfilter
AND "DATE" IN (SELECT MAX(NameofDATE_Column) FROM YourTableName WHERE
anyfilter GROUP BY
TO_CHAR(NameofDATE_Column,'MONTH'),TO_CHAR(NameofDATE_Column,'YYYY'));
Note: this answer does apply for Oracle DB
Here's how I just solved this. day_date is the date field, calendar is the table that holds the dates.
SELECT cast(datepart(year, day_date) AS VARCHAR)
+ '-'
+ cast(datepart(month, day_date) AS VARCHAR)
+ '-'
+ cast(max(DATEPART(day, day_date)) AS VARCHAR) 'DATE'
FROM calendar
GROUP BY datepart(year, day_date)
,datepart(month, day_date)
ORDER BY 1

Check whether two dates contain a given month

My problem is simple... or may be not. I've got a table that contains two dates:
StartDate
EndDate
And I have a constant which is a month. For example:
DECLARE #MonthCode AS INT
SELECT #MonthCode = 11 /* NOVEMBER */
I need a SINGLE QUERY to find all records whose StartDate and EndDate includes the given month. For example:
/* Case 1 */ Aug/10/2009 - Jan/01/2010
/* Case 2 */ Aug/10/2009 - Nov/15/2009
/* Case 3 */ Nov/15/2009 - Jan/01/2010
/* Case 4 */ Nov/15/2009 - Nov/15/2009
/* Case 5 */ Oct/01/2010 - Dec/31/2010
The first and last case need special attention: Both dates are outside November but the cross over it.
The following query does not take care of case 1 and 5:
WHERE MONTH( StartDate ) = #MonthCode OR MONTH( EndDate ) = #MonthCode
The following query also failed because Aug < Nov AND Nov < Jan = false:
WHERE MONTH( StartDate ) = #MonthCode OR MONTH( EndDate ) = #MonthCode OR (
MONTH( StartDate ) < #MonthCode AND #MonthCode < MONTH( EndDate )
)
I understand that you are looking for a way to select all the ranges that intersect November, in any year.
Here is the logic:
if the range falls on a single year (e.g. 2009), the start month must be before or equal to November AND the end month after or equal to November
if the range falls on two subsequent years (e.g. 2009-2010), the start month must be before or equal to November OR the end month after or equal to November
if the range falls on two years with more than 1 year in difference (e.g. 2008-2010), November is always included in the range (here November 2009)
Translated in pseudo-code, the condition is:
// first case
(
(YEAR(StartDate)=YEAR(EndDate)) AND
(MONTH(StartDate)<=MonthCode AND MONTH(EndDate)>=MonthCode)
)
OR
// second case
(
(YEAR(EndDate)-YEAR(StartDate)=1) AND
(MONTH(StartDate)<=MonthCode OR MONTH(EndDate)>=MonthCode)
)
OR
// third case
(
YEAR(EndDate)-YEAR(StartDate)>1
)
DECLARE #MonthCode AS INT
SELECT #MonthCode = 11 /* NOVEMBER */
declare #yourtable table(
startdate datetime
, enddate datetime
)
insert into #yourtable(
startdate
, enddate
)
(
select '8/10/2009', '01/01/2010'
union all
select '8/10/2009' , '11/15/2009'
union all
select '11/15/2009' , '01/01/2010'
union all
select '11/15/2009' , '11/15/2009'
union all
select '10/01/2010' , '12/31/2010'
union all
select '05/01/2009', '10/30/2009'
)
select *
from #yourtable
where DateDiff(mm, startdate, enddate) > #MonthCode -- can't go over 11 months without crossing date
OR (Month(startdate) <= #MonthCode -- before Month selected
AND (month(enddate) >=#MonthCode -- after month selected
OR year(enddate) > year(startdate) -- or crosses into next year
)
)
OR (Month(startdate) >= #MonthCode -- starts after in same year after month
and month(enddate) >= #MonthCode -- must end on/after same month assume next year
and year(enddate) > year(startdate)
)
Try this:
select * from Mytable
where
month(StartDate) = #MonthCode or month(EndDate) = #MonthCode // Nov/15/2009 - Nov/15/2009
or
dateadd(month,#MonthCode-1,convert(datetime,convert(varchar,year(StartDate))))
between StartDate and EndDate // Oct/01/2010 - Dec/31/2010
or
dateadd(month,#MonthCode-1,convert(datetime,convert(varchar,year(EndDate))))
between StartDate and EndDate // Dec/01/2009 - Dec/31/2010 - tricky one
The main ideea is to check where are 01.November.StartYear and 01.November.EndYear dates located.
Hope it helps.
Filter for the rows that start before the end of the month, and end after the start of the month. For October 2009:
select *
from YourTable
where StartDate < '2009-11-01' and EndDate >= '2009-10-01'
Or, with just the month as input:
declare #month datetime
set #month = '2009-10-01'
select *
from YourTable
where StartDate < dateadd(month,1,#month)
and EndDate >= #month
There are various functions you can use to achieve this, like DATEPART and DATETIFF. However, the real problem is not how to express the condition of StartDate or EndDate falling on the given month, but how to do this in a fashion that makes the query efficient. In other words how to express this in a SARGable fashion.
In case you search a small change table, anything under 10k pages, then it doesn't make that much of a difference, a full scan would be probably perfectly acceptable. The real question is if the table(s) are significant in size and a full scan is unacceptable.
If you don't have an index on any of the StartDate or EndDate column it makes no difference, the criteria is not searchable and the query will scan the entire table anyway. However, if there are indexes on StartDate and EndDate the way you express the condition makes all the difference. The critical part for DATETIME indexes is that you must express the search as an exact date range. Expressing the condition as a function depending on the DATETIME field will render the condition unsearchable, resulting in a full table scan. So this knowledge render itself to the correct way searching a date range:
select ... from table
where StartDate between '20091101' and '20091201'
or EndDate between '20091101' and '20091201';
This can be also expressed as:
select ... from table
where StartDate between '20091101' and '20091201'
union all
select ... from table
where EndDate between '20091101' and '20091201'
and StartDate not between '20091101' and '20091201';
Which query works better depends on a number of factors, like your table size and statistics of the actual data in the table.
However, you want the month of November from any year, which this query does not give you. The solution to this problem is against every instinct a programmer has: hard code the relevant years. Most times the tables have a small set of years anyway, something in the range of 4-5 years of past data and plan for 3-4 years more until the system will be overhauled:
select ... from table
where StartDate between '20051101' and '20051201'
or EndDate between '20051101' and '20051201'
union all
select ... from table
where StartDate between '20061101' and '20061201'
or EndDate between '20061101' and '20061201'
union all
...
select ... from table
where StartDate between '20151101' and '20151201'
or EndDate between '20151101' and '20151201';
There are 12 months in a year, write 12 separate procedures. Does this sound crazy? It sure does, but is the optimal thing from the SQL query compiler and optimizer perspective. How can one maintain such code? 12 separate procedure, with a query that repeats itself 10 times (20 times if you use the UNION between StartDate and EndDate to remove the OR), 120 repeats of code, it must be non-sense. Actually, it isn't. Use code generation to create the procedures, like XML/XSLT, so you can easily change it and maintain it. Does the client has to know about the 12 procedures and call the appropriate one? Of course not, it calls one wrapper procedure that discriminates on the #Month argument to call the right one.
I recon that anyone who will looks at the system after the facts will likely believe this query was written by a band of drunk monkeys. Yet somewhere between parameter sniffing, index SARGability and SQL DATETIME quirks the result is that this is the state of the art today when it pertains to searching calendar intervals.
Oh, and if the query hits the Index Tipping Point it will make the whole argument mute anyway...
Update
BTW there is also a cheap way out if you're willing to sacrifice some storage space: two persisted computed columns on StartMonth AS DATEPART(month, StartDate) and EndDate AS DATEPART(month, EndDate), and index on each and query WHERE StartMonth = #Month OR EndMonth = #Month (or again UNION between two queries one for Start one for End, to remove the OR).
SQL Server 200/2005, You can also do this:
select
*
from
table
where
datepart(m,startDate) = 11
and datepart(m,EndDate) = 11
UPDATE:
Removed and datepart(yyyy,startDate) = datepart(yyyy,endDate)
Do want a given month regardless of Year or Day?

SQL date subtraction

In SQL, I'd like to list all funds whose anniversary is due this year in 2 months time. What is the syntax?
SELECT *
FROM dbo.Funds
WHERE AnniversaryDate <= DATEADD(MONTH, 2, GETDATE())
That should work in SQL Server 2000 and up.
Marc
SELECT DATE_ADD(CURDATE(), INTERVAL 2 MONTH);
This will do it in MySQL. I haven't added the anniversary comparison because I don't know the structure of your tables.
I am not quite sure how to interpret your question, but it seems you are after something like this.
SELECT *
FROM funds
WHERE CURRENT_DATE <= anniversary
AND CURRENT_DATE > DATE_SUB(anniversary, INTERVAL 2 MONTH)
It is possibly not exact as I don't know which flavour of SQL you are using.
I don't know if "fund anniversary" is some kind of a special term in English, so I'm assuming you want to select something like the birthdays which can be stored with a random year, like 1972-01-03.
If it's not so, please correct me.
In SQL Server, you need to generate a list of years and join with it:
WITH q AS
(
SELECT 0 AS num
UNION ALL
SELECT num + 1
FROM q
WHERE num <= 100
)
SELECT *
FROM mytable
WHERE fund_date BETWEEN DATE_ADD(year, -num, GETDATE()) AND DATE_ADD(year, -num, DATE_ADD(month, 2, GETDATE()))
UNION ALL
SELECT *
FROM mytable
WHERE fund_date <= DATEADD(year, -100, GETDATE()
AND DATE_ADD(year, YEAR(GETDATE()) - YEAR(fund_date), fund_date) BETWEEN GETDATE() AND DATE_ADD(month, 2, GETDATE()))
This query is built in two parts:
The first part selects birthdays for each year from the list using the index range scans.
The second part selects birthdays that are more than 100 years old (using a single range scan) and filters them all.
Since birthdates older than 100 years are very unlike, the second part in fact selects almost nothing and does not affects performance too much.