How to Find Current Month and Year From Custom Date range? - sql

I have a problem about custom date range. let me explain it, for our company month count from current month day 21 to next month day 20. if i want to know which employee join current month then normally i can find using sql
SELECT *
FROM tblEmployeeMaster
--CURRENT MONTH
WHERE MONTH(DateOfJoining)=MONTH(GETDATE()) AND YEAR(DateOfJoining)=YEAR(GETDATE())
but for this custom date range i can not find employee who are join in this month. For example in this system if i want to find list of employee joined in this month then result will be show that employee who join in previous month after day 21 to current month day 20. Could someone please help me?

In this example, this month's period is considered to be from 21 of the previous month to 20 of current month, employees in that period are considered to be this month's employees (all who came to company after 2012-05-21 until 2012-06-20 (including 2012-06-20)). Try it:
SELECT DateOfJoining,
DATEADD(DAY, 20, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 1, 0)) PeriodStart,
DATEADD(DAY, 19, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) PeriodEnd
FROM tblEmployeeMaster
WHERE DateOfJoining > DATEADD(DAY, 20, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 1, 0))
AND
DateOfJoining < DATEADD(DAY, 20, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))

SELECT *
FROM tblEmployeeMaster
WHERE DateOfJoining BETWEEN CAST(CAST(YEAR(GETDATE()) AS VARCHAR) +'-'+ CAST(MONTH(GETDATE()) AS VARCHAR) +'-21' AS DATETIME)
AND CAST(CAST(YEAR(DATEADD(month,1,GETDATE())) AS VARCHAR) +'-'+ CAST(MONTH(DATEADD(month,1,GETDATE())) AS VARCHAR) +'-20' AS DATETIME)

Related

in mssql get first, second, third weekdate of current month, what date would it be the next month

Given a date lets say Aug 2, 2019 which is first friday of the month. what would be the first friday of next month (sept 6th). Now lets say I have sept 26th which is the last thur of the month. what date would it be for the last thur of next month. I have to do this in MSSQL.
What would you do for the option of September 12th? Sounds like you have two separate scenarios.
In either case, I would use a Date Table or Calendar Table if you have one. If not, set one up. I highly recommend it. Ed Pollock does a great article on what a date table setup would look like here: Designing a Calendar Table. SQLServer.Info has a good example of the table here: Table Example. Second example for good measure Table Setup
Table Setup. This is how it should look. Or at least something similar. You can add more columns to do more comparisons.
Once you have your calendar table set up, its a matter of comparing the date you want to the table.
This is how you can grab the first week of the next month based on a date table
DECLARE #Date DATE = '8/2/2019';
SELECT [dt].Date
FROM [Datetbl] AS [dt]
WHERE [dt].[Weekday] = DATEPART([weekday], DATEADD(day, -1, #Date)) -- is same day of the week
AND [dt].Month = DATEPART(month, DATEADD(MONTH, 1, #Date)) -- Grab the month number for "Next Month"
AND [dt].Year = DATEPART(year, DATEADD(MONTH, 1, #Date)) -- Grab year of next month since that will be different for December
AND [dt].[WeekOfMonth] IN
(SELECT MIN([WeekOfMonth])
FROM [Datetbl] AS [dt1]
WHERE [dt1].[Weekday] = DATEPART([weekday], DATEADD(day, -1, #Date))
AND [dt1].Month = DATEPART(month, DATEADD(MONTH, 1, #Date))
AND [dt1].Year = DATEPART(year, DATEADD(MONTH, 1, #Date))
); -- returns Sept 6
This is how you would go about getting the last weekday of the month based on a date table
DECLARE #Date DATE = '9/26/2019';
SELECT [dt].Date
FROM [Datetbl] AS [dt]
WHERE [dt].[Weekday] = DATEPART([weekday], DATEADD(day, -1, #Date)) -- is same day of the week
AND [dt].Month = DATEPART(month, DATEADD(MONTH, 1, #Date)) -- Grab the month number for "Next Month"
AND [dt].Year = DATEPART(year, DATEADD(MONTH, 1, #Date)) -- Grab year of next month since that will be different for December
AND [dt].[WeekOfMonth] IN
(SELECT MAX([WeekOfMonth])
FROM [Datetbl] AS [dt1]
WHERE [dt1].[Weekday] = DATEPART([weekday], DATEADD(day, -1, #Date))
AND [dt1].Month = DATEPART(month, DATEADD(MONTH, 1, #Date))
AND [dt1].Year = DATEPART(year, DATEADD(MONTH, 1, #Date))
); -- returns Oct 31st
Hope this helps.

Simple SQL Query: need this month data and previous month last 5 days data together

Need SQL query for this month data and previous month last 5 days data together:
SELECT
CONVERT(VARCHAR (10), wDate, 103) AS wDate,
Empid,
Process,
Model,
Qty,
Section,
Avlbl_Mins,
NP_Mins,
L_Mins,
NP_Reason AS NPReason,
Process_Remarks AS PRem,
Day_Remarks AS DRem,
Othermin,
StdMin,
Tstdmin,
TAvlblmin
FROM tblProductionEffcyDetails
WHERE (DAY(EnteredDate) >= DAY(GETDATE()) - 5)
ORDER BY EnteredDate DESC
Try this : to get data from last months last five days
WHERE EnteredDate > (DATEADD(DAY,-5,DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0))
For SQL SERVER 2012+ use this
WHERE EnteredDate >= dateadd(dd,-4,eomonth(getdate(),-1))
and EnteredDate < dateadd(dd,1,eomonth(getdate()))
For older versions
WHERE EnteredDate >= dateadd(dd,-5,DATEADD(month, DATEDIFF(month, 0, getdate()), 0))
and EnteredDate < DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, getdate()) + 1, 0))

SQL: How to get the following day from end of the month

Example:
If I run this query today (26 January), my result will be addedon +1 day which is 27 January.
select addedon
from member
Where Day(addedon) = Day(DateAdd(dd, 1, GetDate()))
and Month(addedon) = Month(DateAdd(dd, 1, GetDate()))
However, when I run this query on 31 January, it is giving me 1 January result instead of 1 Feb.
Please help! Note that I can only use simple select statement (like the above) in my application.
To get the beginning of the next month:
SELECT DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) + 1, 0)
This will return member whose addedon falls on the first day of the next month.
SELECT addedon
FROM member
WHERE
addedon >= DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) + 1, 0)
AND addedon < DATEADD(DD, 1, DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) + 1, 0))
This will return member whose addedonfalls on the next day:
SELECT addedon
FROM #member
WHERE
addedon >= DATEADD(DD, DATEDIFF(DD, 0, GETDATE()) + 1, 0)
AND addedon < DATEADD(DD, DATEDIFF(DD, 0, GETDATE()) + 2, 0)
I'm going to guess that your datetime are - as is pretty typical - stored in your database as UTC datetime, and that you are somewhere in the Western Hemisphere, and that calling Month on a UTC time after, say, 9:30EDT (or 8:30CDT) is returning 2, matching Month(DateAdd(dd, 1, GetDate())).
Most of the time, you want to store your datetime in your database as UTC, which means - most of the time - you want to write your queries the same way (i.e., using GetUtcDate).
As a test, rewrite you query using GetUtcDate in place of GetDate, and see if your results change.

How to get first day of the week and last day of the week in sql server 2008?

How to get the first day of the week and last day of the week when we input any one day of a week?
For example if we enter a date then the first(Monday) and last (Friday) day should be displayed.
that is if we enter 24-jan-2014 then 20-jan-2014 and 24-jan-2014 should be displayed.
Regards
Here's how you can do it:
DECLARE #yourdate date = getdate()
Select dateadd(ww, datediff(ww, 0, #yourdate), 0)
Select dateadd(ww, datediff(ww, 0, #yourdate), 4)
You set #yourdate to the date you want. The first SELECT will give you the first day and the second SELECT will give you the last date
This solves it and also wraps around year ends:
SELECT DATEADD(wk, DATEDIFF(d, 0, '01 January 2017') / 7, 0)
Try this
SELECT DATEADD(wk, DATEDIFF(wk, 6, '5/13/2005'), 6)
SELECT DATEADD(wk, DATEDIFF(wk, 5, '5/13/2005'), 5)
(Or)
Declare #Date datetime
Det #Date = '2012-04-12'
Delect #Date - DATEPART(dw, #Date) + 1 FirstDateOfWeek,
#Date + (7 - DATEPART(dw, #Date)) LastDateOfWeek
With a calendar date already loaded, group can be done like this for all the years existing in the table =)
select
Y,
M,
(Select dateadd(ww, datediff(ww, 0, dt), 0) ) wk_str_dt ,
(Select dateadd(ww, datediff(ww, 0, dt), 4) )wk_end_dt ,
dt recd_crt_dt
from [tcalendar]
where isWeekday= 1
AND DW = 2 -- only mondays
order by Y, W

SQL Date Function

I may be using the wrong term (hence why I can't find it on google).
"Are there any functions or common code for Accounting Months Deliminations?"
For Example, this month started on a friday but on most accounting journals the weeks are measured by the first monday of the month so instead of having the 1st of July it would be the 4th of July. Same thing with the month end (29th instead of the 31st)
Again, I'm sure someone has created this 'wheel' before, and I can't seem to find it for the life of me.
The following query assumes a table, SalesTable, has a field called Amount (the value you want to sum) and a field called SaleDate (the date on which the sale occured.) It also assumes that accounting months begin the first Monday of the month and end on the Sunday prior to the beginning of the next accounting month.
Again, I highly recommend a table-based approach to this, but if you can't modify the schema, this should do the trick in T-SQL:
SELECT
CASE WHEN s.SaleDate < DATEADD(WEEK, DATEDIFF(WEEK, 0, DATEADD(DAY, 6 - DATEPART(DAY, s.SaleDate ),s.SaleDate )), 0)
THEN DATEADD(WEEK, DATEDIFF(WEEK, 0, DATEADD(DAY, 6 - DATEPART(DAY, DATEADD(day,-7,s.SaleDate) ),DATEADD(day,-7,s.SaleDate) )), 0)
ELSE DATEADD(WEEK, DATEDIFF(WEEK, 0, DATEADD(DAY, 6 - DATEPART(DAY, s.SaleDate ),s.SaleDate )), 0)
END AccountingMonth,
SUM(s.Amount) TotalSales
FROM SalesTable s
GROUP BY
CASE WHEN s.SaleDate < DATEADD(WEEK, DATEDIFF(WEEK, 0, DATEADD(DAY, 6 - DATEPART(DAY, s.SaleDate ),s.SaleDate )), 0)
THEN DATEADD(WEEK, DATEDIFF(WEEK, 0, DATEADD(DAY, 6 - DATEPART(DAY, DATEADD(day,-7,s.SaleDate) ),DATEADD(day,-7,s.SaleDate) )), 0)
ELSE DATEADD(WEEK, DATEDIFF(WEEK, 0, DATEADD(DAY, 6 - DATEPART(DAY, s.SaleDate ),s.SaleDate )), 0)
END
Note that the AccountingMonth return field actually contains the date of the first Monday of the month. In actual practice, you probably want to wrap this entire query in another query that reformats AccountingMonth to whatever you like... "2011-07", "2011-08", etc.
Here's how it works: This bit of code is the important part:
DATEADD(WEEK, DATEDIFF(WEEK, 0, DATEADD(DAY, 6 - DATEPART(DAY, s.SaleDate ),s.SaleDate )), 0)
It takes any date and returns the first Monday of the month in which that date occurred. In your case, however, you have to do a little more work because a sale might have occurred in the window between the first of the month and the first Monday of the month. The CASE statement detects that scenario and, if it's true, subtracts a week off of the date before calculating the first Monday.
Good luck!
-Michael
I have some code that takes in a year and month and returns the fiscal start and end dates. Perhaps this will give you something to go by:
DECLARE #yr int;
DECLARE #mo int;
SELECT #yr = 2011
SELECT #mo = 7
DECLARE #FiscalMonthStartDate datetime
DECLARE #FiscalMonthEndDate datetime
DECLARE #startOfMonth datetime
DECLARE #startOfNextMonth datetime
select #startOfMonth = CAST((CAST(#yr AS VARCHAR(4)) + '-' + CAST(#mo AS VARCHAR(2)) + '-' + '01') as DATE)
select #startOfNextMonth = CAST((CAST(#yr AS VARCHAR(4)) + '-' + CAST((#mo + 1) AS VARCHAR(2)) + '-' + '01') as DATE)
SELECT #FiscalMonthStartDate =
CASE
WHEN DATEPART(DW,#startOfMonth) = 0
THEN DATEADD(DD, 1, #startOfMonth)
ELSE
DATEADD(DD, 8 - DATEPART(DW,#startOfMonth), #startOfMonth)
END
SELECT #FiscalMonthEndDate =
CASE
WHEN DATEPART(DW,#startOfNextMonth) = 0
THEN DATEADD(DD, 1, #startOfNextMonth)
ELSE
DATEADD(DD, 8 - DATEPART(DW,#startOfNextMonth), #startOfNextMonth)
END
-- subtract one day to get end of fiscal month (not start of next fiscal month)
SELECT #FiscalMonthEndDate = DATEADD(DD, -1, #FiscalMonthEndDate)
SELECT #FiscalMonthStartDate, #FiscalMonthEndDate