Query View to show current week days - sql-server

I am trying to show the current weekdays of the week I am in when I run my query but I am getting an error message. I had seen a post on here that I had copied the code and it worked but somehow my query got changed and is now not working. Here is the code I copied and when it ran it showed a list of the current dates of this week.
WITH DAYSOFTHEWEEK
AS
(
SELECT 0 AS DAY
UNION ALL
SELECT DAY + 1 AS Expr1
FROM dbo.DaysoftheWeek AS DAYSOFTHEWEEK_2
WHERE (DAY < 4)
)
SELECT DATEADD(DAY, DAY, DATEADD(DAY, 2 - DATEPART(WEEKDAY, CONVERT(DATE, GETDATE())), CONVERT(DATE, GETDATE()))) AS DAY_OF_THE_WEEK
FROM DAYSOFTHEWEEK AS DAYSOFTHEWEEK_1
GROUP BY DAY

Remove dbo from the WITH Clause.
Try This
WITH DAYSOFTHEWEEK
AS
(
SELECT 0 AS DAY
UNION ALL
SELECT DAY + 1 AS Expr1
FROM DaysoftheWeek AS DAYSOFTHEWEEK_2
WHERE (DAY < 4)
)
SELECT DATEADD(DAY, DAY, DATEADD(DAY, 2 - DATEPART(WEEKDAY, CONVERT(DATE, GETDATE())), CONVERT(DATE, GETDATE()))) AS DAY_OF_THE_WEEK
FROM DAYSOFTHEWEEK AS DAYSOFTHEWEEK_1
GROUP BY DAY

Related

Generate counts of records for each day in a week

I use SQL Server 2014 for my project. I have the following code to produce the number of registrations of each day:
SELECT
DATEADD(DAY, DATEDIFF(DAY, 0, createTime), 0) AS createdOn,
COUNT(*) AS Count
FROM
Registration
GROUP BY
DATEADD(DAY, DATEDIFF(DAY, 0, createTime), 0)
ORDER BY
createdOn
Now I would like to get the numbers for each day in a week (so there will be max 7 rows in output). How can I do it?
Here is the solution I have based on George's comment. Thank you, George!
SELECT
DATEPART(weekday, createTime) AS createdOn,
COUNT(*) AS Count
FROM
Registration
GROUP BY
DATEPART(weekday, createTime)
ORDER BY
createdOn
One way to return all days within a range returned with your data joined on matching days is to use a "calendar" table and LEFT JOIN your data by date.
DECLARE #StartDate DATETIME = '01/01/2015'
DECLARE #EndDate DATETIME = '12/01/2016'
//By Day In Year
;WITH Calender as
(
SELECT CalendarDate = #StartDate
UNION ALL
SELECT CalendarDate = DATEADD(DAY, 1, CalendarDate)
FROM Calender WHERE DATEADD (DAY, 1, CalendarDate) <= #EndDate
)
SELECT
C.CalendarDate,
COUNT(*) AS Count
FROM
Calender C
LEFT JOIN Regsitration R ON R.createdOn = C.CalendarDate
GROUP BY
C.CalendarDate
OPTION (MAXRECURSION 0)
//By Week In Year
;WITH Calender as
(
SELECT CalendarDate = #StartDate, WeekNumber=DATEPART(WEEK, #StartDate)
UNION ALL
SELECT CalendarDate = DATEADD(WEEK, 1, CalendarDate), WeekNumber=DATEPART(WEEK, #StartDate)
FROM Calender WHERE DATEADD (WEEK, 1, CalendarDate) <= #EndDate
)
SELECT
C.WeekNumber,
COUNT(*) AS Count
FROM
Calender C
LEFT JOIN Regsitration R ON DATEPART(WEEK,R.createdOn) = C.WeekNumber
GROUP BY
C.WeekNumber
OPTION (MAXRECURSION 0)

How to get date from day name?

How can I get the date of specific day ? Like if I have Thursday or month number ?
If I give 12 for instance I want to get the date of 12th day of this month. Or if I give 'Sun' or 'Sat' is it possible to get the dates of these days ?
DATEFROMPARTS function can construct a date from day, month and year.
DATEPARTS does the opposite - gives you the day, month, year, hour, etc. of a date. Or you can use functions like YEAR, MONTH and DAY.
You can deconstruct the value returned by GETDATE function and construct whatever date you want. Here is for example how to get the date for 12th day of the current month:
select DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 12)
Converting 'Sun' or 'Sat' to date is a bit more difficult. First, they aren't quite deterministic. If today is Friday, "Sunday this week" means "next Sunday" in some parts of the world and "last Sunday" in others. You should implement your own logic based on the value returned by DATEPART(dw, GETDATE()) (which will give you the day of the week).
To find the weekday of the current month
DECLARE #daynumber INT = 12
SELECT datename(weekday, dateadd(d, #daynumber - 1, getdate()))
To find the dates of the current month of a given weekday
DECLARE #dayname char(3) = 'sat'
;WITH CTE as
(
SELECt TOP
(datediff(D, eomonth(getdate(), -1),eomonth(getdate())))
dateadd(d,row_number()over(ORDER BY 1/0),
eomonth(getdate(),-1))date
FROM
(values(1),(2),(3),(4),(5),(6))x(x),
(values(1),(2),(3),(4),(5),(6))y(x)
)
SELECT day(date) monthday, date
FROM CTE
WHERE left(datename(weekday, date),3) = #dayname
select sysdatetime(); --2018-12-13 16:29:56.0560574
---If I give 12 for instance I want to get the date of 12th day of this month.
declare #numDate int = 12;
select dateadd(m, datediff(m,0,getdate()),#numDate - 1 ); --2018-12-12 00:00:00.000
--Or if I give 'Sun' or 'Sat' is it possible to get the dates of these days ?
declare #text nvarchar(20) = 'Sunday';
declare #dateStart date = dateadd(month, datediff(month, 0, sysdatetime()), 0),
#days int =( select (DAY(dateadd(dd,-1,DATEADD(m,1,cast(2018 as varchar(4)) + '-' + cast(12 as varchar(2)) +'-01')))));
declare #dateEnd date = DATEADD(day,#days-1,#dateStart);
;WITH CTE (Dates,EndDate) AS
(
SELECT #dateStart AS Dates,#dateEnd AS EndDate
UNION ALL
SELECT DATEADD(day,1,Dates),EndDate
FROM CTE
WHERE DATEADD(day,1,Dates) <= EndDate
)
SELECT CTE.Dates, DATENAME(DW, CTE.Dates)
FROM CTE
where DATENAME(DW, CTE.Dates) = #text;
Result:
Dates,Day
2018/12/2,Sunday
2018/12/9,Sunday
2018/12/16,Sunday
2018/12/23,Sunday
2018/12/30,Sunday
-- Here is how to get week day name to week day number
DECLARE #T TABLE (Dow INT, NameOfDay VARCHAR(15), ShortName CHAR(3));
WITH Days AS
(
SELECT TOP 7
ROW_NUMBER() OVER(PARTITION BY object_id ORDER BY object_id) AS RowNo
FROM
sys.all_columns
)
INSERT INTO #T
SELECT
RowNo,
DATENAME(WEEKDAY, RowNo - 1),
LEFT(DATENAME(WEEKDAY, RowNo - 1), 3)
FROM
Days
SELECT
*
FROM
#T;
-- Here is how to get start of period
SELECT
DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0) AS StartOfDay,
DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 0) AS StartOfWeek,
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) AS StartOfMonth,
DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0) AS StartOfYear;
-- An example
WITH
StartPeriods AS
(
SELECT DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 0) AS StartOfWeek
),
SelectedDay AS
(
SELECT
Dow - 1 AS Dow,
(SELECT StartOfWeek FROM StartPeriods) AS StartOfWeek
FROM
#T
WHERE
ShortName = 'Wed'
)
SELECT
DATEADD(DAY, Dow, StartOfWeek)
FROM
SelectedDay;

List of Employees who are not in the list one day before and one day after weekend

I need list of those employees who are absent one day before and one day after weekend in a week......like if some is absent in Friday and present on Monday should not be included in the list
Use datepart(weekday, ) to fetch all records relative to monday and friday.
Have a look at SET DATEFIRST function too.
select *
from your_table
where datepart(weekday, Date) = 5
or datepart(weekday, Date) = 1;
This will list all employee id that are absent on a Friday and the following Monday (+1 week). I set-up a calendar week from mininum date to maximum date from the table and get only Friday and Monday. Then get all empid that has no attendance in any of those dates.
with caldte as (
SELECT dateadd(day, rn - 1, t.mindte) as dates,
datepart(weekday, dateadd(day, rn - 1, t.mindte)) as weekday,
datepart(wk, dateadd(day, rn - 1, t.mindte)) as weeknum
FROM (
select row_number() OVER ( order by c.object_id ) AS rn
FROM sys.columns c) rns,
(select min(dte) as mindte, max(dte) as maxdte
from tbl) t
WHERE rn - 1 <= datediff(day, t.mindte, t.maxdte)
and datepart(weekday, dateadd(day, rn - 1, t.mindte)) in (2, 6)
)
select distinct empid
from tbl
where empid not in (
select t.empid
from caldte c, tbl t
where c.dates = t.dte)
order by empid

tSQL select previous 3 months

Im not a sql person and have been thrust into being one :\
Im trying to get the previous 3 months of data without the current month.
WHERE DATEPART(m, start_date) = DATEPART(m, DATEADD(m, -3, getdate()))
and DATEPART(yyyy, start_date) = DATEPART(yyyy, DATEADD(m, -3, getdate()))
this gets me the data from January only, i need Jan-Mar.
WHERE start_date >= dateadd(mm,datediff(mm,0,getdate())-3,0)
and this gets me everything from jan 1st - now.
So now im stuck and not sure what to do.
mssql ver: 2012
Thank you in advance for any help.
WHERE DateColumn >= DATEADD(MONTH,DATEDIFF(MONTH,0,GETDATE()) -3,0)
AND DateColumn < DATEADD(MONTH,DATEDIFF(MONTH,0,GETDATE()) ,0)
This will return the data from Between 2015-01-01 and 2015-03-31
You can try this:
Where datediff(mm, start_date, getdate()) in (1, 2, 3)
Does this helps?:
WHERE start_date BETWEEN DATEADD(m, -3, getdate()) AND DATEADD(m, -1, getdate())
You can use something like this:
WHERE MONTH(start_date)>= MONTH(getdate())- 3 AND MONTH(start_date)< MONTH(getdate())
You can build a string and convert it to a date... such as:
WHERE start_date >= dateadd(month,-3, convert(datetime,convert(varchar(10),Month(GETDATE())) + '/01/' + convert(varchar(10),Year(GETDATE()))))
and start_date < convert(datetime,convert(varchar(10),Month(GETDATE())) + '/01/' + convert(varchar(10),Year(GETDATE())))
SELECT DATEADD(MONTH,DATEDIFF(MONTH,0,DATEADD(MONTH,-3,GETDATE())),0) -- FIRST DAY OF MONTH, THREE MONTHS AGO
,DATEADD(MILLISECOND,-3,DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) -- LAST DAY OF LAST MONTH

how to get data of current week only in SQL server?

I want records from table which stores the current date when a record is inserted with in current week only.
I have tried:
SELECT PId
,WorkDate
,Hours
,EmpId
FROM Acb
WHERE EmpId=#EmpId AND WorkDate BETWEEN DATEADD(DAY, -7, GETDATE()) AND GETDATE()
Do it like this:
SET DATEFIRST 1 -- Define beginning of week as Monday
SELECT [...]
AND WorkDate >= dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate()))
AND WorkDate < dateadd(day, 8-datepart(dw, getdate()), CONVERT(date,getdate()))
Explanation:
datepart(dw, getdate()) will return the number of the day in the current week, from 1 to 7, starting with whatever you specified using SET DATEFIRST.
dateadd(day, 1-datepart(dw, getdate()), getdate()) subtracts the necessary number of days to reach the beginning of the current week
CONVERT(date,getdate()) is used to remove the time portion of GETDATE(), because you want data beginning at midnight.
A better way would be
select datepart(ww, getdate()) as CurrentWeek
You can also use wk instead of ww.
Datepart Documentation
Its Working For Me.
Select * From Acb Where WorkDate BETWEEN DATEADD(DAY, -7, GETDATE()) AND DATEADD(DAY, 1, GETDATE())
You have to put this line After the AND Clause AND DATEADD(DAY, 1, GETDATE())
datepart(dw, getdate()) is the current day of the week, dateadd(day, 1-datepart(dw, getdate()), getdate()) should be the first day of the week, add 7 to it to get the last day of the week
You can use following query to extract current week:
select datepart(dw, getdate()) as CurrentWeek
SET DATEFIRST 1;
;With CTE
AS
(
SELECT
FORMAT(CreatedDate, 'MMMM-yyyy') as Months,
CASE
WHEN YEAR(DATEADD(DAY, 1-DATEPART(WEEKDAY, Min(CreatedDate)), Min(CreatedDate))) < YEAR(Min(CreatedDate))
THEN FORMAT(DATEADD(YEAR, DATEDIFF(YEAR, 0,DATEADD(YEAR, 0 ,GETDATE())), 0) ,'MMM dd') + ' - ' + FORMAT(DATEADD(dd, 7-(DATEPART(dw, Min(CreatedDate))), Min(CreatedDate)) ,'MMM dd')
ELSE
FORMAT(DATEADD(DAY, 1-DATEPART(WEEKDAY, Min(CreatedDate)), Min(CreatedDate)) ,'MMM dd') + ' - ' + FORMAT(DATEADD(dd, 7-(DATEPART(dw, Min(CreatedDate))), Min(CreatedDate)) ,'MMM dd')
END DateRange,
Sum(ISNULL(Total,0)) AS Total,
sum(cast(Duration as int)) as Duration
FROM TL_VriandOPI_Vendorbilling where VendorId=#userID and CompanyId=#CompanyID
Group By DATEPART(wk, CreatedDate) ,FORMAT(CreatedDate, 'MMMM-yyyy')
)
SELECT Months,DateRange,Total,Duration,
case when DateRange=(select FORMAT(DATEADD(DAY, 1-DATEPART(WEEKDAY, Min(getdate())), Min(getdate())) ,'MMM dd') + ' - ' +
FORMAT(DATEADD(dd, 7-(DATEPART(dw, Min(getdate()))), Min(getdate())) ,'MMM dd'))
then 1 else 0 end as Thisweek
FROM CTE order by Months desc
Using DATEDIFF works as well, however a bit hacky since it doesn't care about datefirst:
set datefirst 1; -- set monday as first day of week
declare #Now datetime = '2020-09-28 11:00';
select *
into #Temp
from
(select 1 as Nbr, '2020-09-22 10:00' as Created
union
select 2 as Nbr, '2020-09-25 10:00' as Created
union
select 2 as Nbr, '2020-09-28 10:00' as Created) t
select * from #Temp where DATEDIFF(ww, dateadd(dd, -##datefirst, Created), dateadd(dd, -##datefirst, #Now)) = 0 -- returns 1 result
select * from #Temp where DATEDIFF(ww, dateadd(dd, -##datefirst, Created), dateadd(dd, -##datefirst, #Now)) = 1 -- returns 2 results
drop table #Temp

Resources