I have a database that stores the log-in and log-out of the employees but we don't have work on weekends. My supervisor want the DTR report format(I'm using RDLC report) include the weekends. (see attached image)
The image above is the expected output format for DTR. I just want to know how to include Weekends though my data are on weekdays only. Is it possible to do this using SQL Query? If yes, should I use looping in sql here?
SQL Code:
select user_id,log_date,login_time,logout_time
from table_DTR
where user_id = 'USER1'
AND log_date BETWEEN '11/21/2014' AND '12/09/2014'
Use common table expression and generate date range with from and to date and than use CTE as left join to actual table. I haven't used user_id filter in left join so apply it to your query:
DECLARE @TMEP TABLE
(
[Date] DATE,
[IN] VARCHAR(10),
[OUT] VARCHAR(10)
)
INSERT INTO @TMEP VALUES ('2014-11-11','7:30','5:30')
INSERT INTO @TMEP VALUES ('2014-11-12','7:30','5:30')
INSERT INTO @TMEP VALUES ('2014-11-13','7:30','5:30')
INSERT INTO @TMEP VALUES ('2014-11-14','7:30','5:30')
INSERT INTO @TMEP VALUES ('2014-11-15','7:30','5:30')
INSERT INTO @TMEP VALUES ('2014-11-18','7:30','5:30')
INSERT INTO @TMEP VALUES ('2014-11-19','7:30','5:30')
INSERT INTO @TMEP VALUES ('2014-11-20','7:30','5:30')
INSERT INTO @TMEP VALUES ('2014-11-21','7:30','5:30')
INSERT INTO @TMEP VALUES ('2014-11-22','7:30','5:30')
INSERT INTO @TMEP VALUES ('2014-11-25','7:30','5:30')
INSERT INTO @TMEP VALUES ('2014-11-26','7:30','5:30')
INSERT INTO @TMEP VALUES ('2014-11-27','7:30','5:30')
INSERT INTO @TMEP VALUES ('2014-11-28','7:30','5:30')
INSERT INTO @TMEP VALUES ('2014-11-29','7:30','5:30')
INSERT INTO @TMEP VALUES ('2014-12-1','7:30','5:30')
INSERT INTO @TMEP VALUES ('2014-12-2','7:30','5:30')
INSERT INTO @TMEP VALUES ('2014-12-3','7:30','5:30')
INSERT INTO @TMEP VALUES ('2014-12-4','7:30','5:30')
DECLARE @FromDate DATE
SET @FromDate = '2014-11-11 06:00:00.000'
DECLARE @ToDate DATE
SET @ToDate = '2014-12-11 06:00:00.000'
;WITH CTE_TableDate ([CTEDate]) as
(
SELECT @FromDate
UNION ALL
SELECT DATEADD(DAY,1,CTEDate) FROM CTE_TableDate WHERE [CTEDate] < @ToDate
)
SELECT
CTE_TableDate.CTEDate,
CASE WHEN DATEPART(DW, CTE_TableDate.CTEDate) = 7 THEN 'SATURDAY'
WHEN DATEPART(DW, CTE_TableDate.CTEDate) = 1 THEN 'SUNDAY'
ELSE TEMP.[In] END AS [IN],
CASE WHEN DATEPART(DW, CTE_TableDate.CTEDate) = 7 THEN 'SATURDAY'
WHEN DATEPART(DW, CTE_TableDate.CTEDate) = 1 THEN 'SUNDAY'
ELSE TEMP.[OUT] END AS [OUT]
FROM CTE_TableDate
LEFT JOIN
(
select
[Date],
[IN],
[OUT]
from
@TMEP) TEMP
ON
CTE_TableDate.CTEDate = TEMP.[Date]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments