What I want is the EmployeeName from the emp_mst table with some condition which is given below:-
All EmployeeName for last 7 months from the current date and also less 15 days.
from the below query I am getting the result for the last month, but I want this for the last 6 months
select DATEADD(month, -1, GETDATE()- 15)
I am using sql server 2008
UPDATED PROCEDURE
SELECT * FROM (SELECT CASE
WHEN (SELECT Isnull(Sum(total_day), 0)
FROM xxacl_erp_ab_pl_count_view
WHERE emp_card_no = em.emp_card_no) > 7 THEN
'DOC Exteded By 1 month. Reason:- Taken leave='
+ CONVERT(VARCHAR, (SELECT Sum(total_day) FROM
xxacl_erp_ab_pl_count_view
WHERE emp_card_no = em.emp_card_no))
+
' which is > 7. Actual DOC='
+ CONVERT(VARCHAR, Dateadd(mm, em.probation_period, em.date_of_joining), 103)
+ ''
ELSE 'N/A'
END Remark,
em.*
FROM emp_mst em
LEFT JOIN company_mst comp
ON em.comp_mkey = comp.mkey
AND comp.fa_year = 2008
AND company_name NOT LIKE '%HELIK%'
WHERE em.status IN ( 'A' ) --and em.emp_type='E'
AND em.emp_card_no != 9999
AND em.resig_date IS NULL
AND CONVERT(DATETIME, em.date_of_joining, 103) >=
CONVERT(DATETIME,
Dateadd(m, -6, Getdate()), 103)
AND em.emp_card_no NOT IN (SELECT emp_card_no
FROM p_emp_confirmation_hdr
WHERE delete_flag = 'N'
AND hr_flag = 'Y')) pp
WHERE remark = 'N/A'
Casting to date to avoid calculating with timestamps
WHERE
yourdate >= dateadd(m, -6, datediff(d, 15, getdate())) and
yourdate < dateadd(d, -15, datediff(d, 0, getdate()))
Changed answer to adjust for you using sqlserver 2005 or older
Added 15 days extra to the interval
SELECT [emp_name]
FROM [TABLE]
WHERE [DateColumn] BETWEEN DATEADD(MONTH, -6, CAST(GETDATE() AS DATE))
AND DATEADD(DAY, -15, CAST(GETDATE() AS DATE))
This will show you employees who were added between six months ago and 15 days ago, for example, running that today would give you employees from the range 2014-12-24 and 2015-06-09.
EDIT: For SQL Server 2005 and earlier:
SELECT [emp_name]
FROM [TABLE]
WHERE [DateColumn] BETWEEN DATEADD(MONTH, -6, cast(convert(char(11), getdate(), 113) as datetime))
AND DATEADD(DAY, -15, cast(convert(char(11), getdate(), 113) as datetime))
Related
I'm working on a SQL query trying to fetch sum data for the current day/date. Can anyone have a look at my query, and find me a working solution?
SELECT SUM(amount)
FROM tbl_expense_record
WHERE dateonly = CAST(GETDATE() AS Date)
But I get data when mentioning a specific date in where condition like
SELECT SUM(amount) AS total
FROM tbl_expense_record
WHERE dateonly = '2020-06-12'
I want the a code to auto pick current date. Also I would like to fetch sum of ranged dates like a whole week, and a month!
select datename(month, '2020-06-12'), datename(month, getdate());
--1week
SELECT SUM(amount) AS total
FROM tbl_expense_record
WHERE dateonly >= dateadd(week, -1, cast(getdate() as date))
and dateonly <= cast(getdate() as date)
--1month
SELECT SUM(amount) AS total
FROM tbl_expense_record
WHERE dateonly >= dateadd(month, -1, cast(getdate() as date))
and dateonly <= cast(getdate() as date)
--build muscle memory (it is always safe to check for < date+1 instead of <= date)
--1month
SELECT SUM(amount) AS total
FROM tbl_expense_record
WHERE dateonly >= dateadd(month, -1, cast(getdate() as date))
and dateonly < dateadd(day, 1, cast(getdate() as date));
--6months
SELECT SUM(amount) AS total
FROM tbl_expense_record
WHERE dateonly >= dateadd(month, -6, cast(getdate() as date))
and dateonly < dateadd(day, 1, cast(getdate() as date));
if not exists
(
select *
FROM tbl_expense_record
WHERE dateonly >= dateadd(month, -1, cast(getdate() as date))
and dateonly < dateadd(day, 1, cast(getdate() as date))
)
begin
select 'no rows within the last month'
end
else
begin
select 'there are rows within the last month';
end;
Examples:
declare #tbl_expense_record table(dateonly date, amount decimal(9,2));
insert into #tbl_expense_record
values ('20200501', 10), ('20200612', 10), ('20200613', 11), ('20200614', 12),
('20200710', 5), ('20200720', 6), ('20200820', 20), ('20200825', 30),
('20201102', 1), ('20201110', 2), ('20201120', 3);
--aggregation per month, for all rows
select year(dateonly) as _year, month(dateonly) as _month, sum(amount) as sum_amount_per_month, count(*) as rows_per_month
from #tbl_expense_record
group by year(dateonly), month(dateonly);
--aggregation per iso-week
select year(dateonly) as _year, datepart(iso_week, dateonly) as _isoweek, sum(amount) as sum_amount_per_isoweek, count(*) as rows_per_isoweek
from #tbl_expense_record
group by year(dateonly), datepart(iso_week, dateonly);
--aggregation per month, for all rows with a dateonly that falls in the last month
--check the difference between aggregation per month earlier and this..
--filter rows first == where .... and then aggregate
--there are two rows with dateonly > 06 november (the row at 05 is filtered out by the where clause)
select year(dateonly) as _year, month(dateonly) as _month, sum(amount) as sum_amount_per_month, count(*) as rows_per_month
from #tbl_expense_record
where dateonly >= dateadd(month, -1, cast(getdate() as date))
and dateonly < dateadd(day, 1, cast(getdate() as date))
group by year(dateonly), month(dateonly);
--aggregate per week diff from today/getdate()
select
datediff(week, getdate(), dateonly) as week_diff_from_today,
dateadd(day,
--datepart(weekday..) is used...account for ##datefirst setting / set datefirst
1-(##datefirst+datepart(weekday, dateadd(week, datediff(week, getdate(), dateonly), cast(getdate() as date))))%7,
dateadd(week, datediff(week, getdate(), dateonly), cast(getdate() as date)))
as startofweek,
dateadd(day, 6, --add 6 days to startofweek
dateadd(day,
--datepart(weekday..) is used...account for ##datefirst setting / set datefirst
1-(##datefirst+datepart(weekday, dateadd(week, datediff(week, getdate(), dateonly), cast(getdate() as date))))%7,
dateadd(week, datediff(week, getdate(), dateonly), cast(getdate() as date)))
) as endofweek,
sum(amount) as sum_amount, count(*) as rows_within_week
from #tbl_expense_record
group by datediff(week, getdate(), dateonly);
This is part of a query that is calculating the total revenue for a contract based on the time-frame "This Week" along with the start and end dates of the contract (billed hourly).
SELECT (ChargeRate - PayRate) * 8 *
CASE
WHEN ContractStartDate <= DATEADD(DAY, 1-DATEPART(WEEKDAY, CURRENT_TIMESTAMP), CURRENT_TIMESTAMP)
AND ContractEndDate >= CURRENT_TIMESTAMP
THEN DATEDIFF(DAY, DATEADD(DAY, 1-DATEPART(WEEKDAY, CURRENT_TIMESTAMP), CURRENT_TIMESTAMP), CURRENT_TIMESTAMP)
WHEN ContractEndDate <= CURRENT_TIMESTAMP
AND ContractEndDate >= DATEADD(DAY, 1-DATEPART(WEEKDAY, CURRENT_TIMESTAMP), CURRENT_TIMESTAMP)
AND ContractStartDate <= CURRENT_TIMESTAMP
THEN DATEDIFF(DAY, DATEADD(DAY, 1-DATEPART(WEEKDAY, ContractEndDate), ContractEndDate), ContractEndDate)
WHEN ContractStartDate >= DATEADD(DAY, 1-DATEPART(WEEKDAY, CURRENT_TIMESTAMP), CURRENT_TIMESTAMP)
AND ContractStartDate <= CURRENT_TIMESTAMP
AND ContractStartDate >= CURRENT_TIMESTAMP
THEN DATEDIFF(DAY, ContractStartDate, CURRENT_TIMESTAMP)
WHEN ContractEndDate <= CURRENT_TIMESTAMP
AND ContractEndDate >= DATEADD(DAY, 1-DATEPART(WEEKDAY, CURRENT_TIMESTAMP), CURRENT_TIMESTAMP)
AND ContractStartDate >= CURRENT_TIMESTAMP
THEN DATEDIFF(DAY, ContractStartDate, ContractEndDate)
ELSE DATEDIFF(DAY, DATEADD(DAY, 1-DATEPART(WEEKDAY, CURRENT_TIMESTAMP), CURRENT_TIMESTAMP), CURRENT_TIMESTAMP)
END
What i am struggling with is how i can exclude Saturday and Sunday so the count never goes past 5 and where Sunday is not the start of the week but instead Monday. So the number of days worked would end up being [ Monday = 1, Tuesday = 2 ... Friday = 5, Saturday = 5, Sunday = 5 ] based on what day the query is run.
What happens at the moment is that if these graphs are run on Saturday the calculation uses 6 days, if its run on Sunday the calculation uses 0 days. Every day during the week is correct, this can be seen with the following query:
DECLARE #StartDate DATETIME = '2019-12-1'
DECLARE #StartDate2 DATETIME = '2019-11-30'
SELECT DATEDIFF(DAY, DATEADD(DAY, 1-DATEPART(WEEKDAY, #StartDate), #StartDate), #StartDate)
SELECT DATEDIFF(DAY, DATEADD(DAY, 1-DATEPART(WEEKDAY, #StartDate2), #StartDate2), #StartDate2)
Results should be 0 and 6.
The only solution i can come up with is to nest the case statement and check if the value = 0 or 6 and change it to a 5, like so:
WHEN ContractStartDate <= DATEADD(DAY, 1-DATEPART(WEEKDAY, CURRENT_TIMESTAMP), CURRENT_TIMESTAMP)
AND ContractEndDate >= CURRENT_TIMESTAMP
THEN
CASE
WHEN DATEDIFF(DAY, DATEADD(DAY, 1-DATEPART(WEEKDAY, CURRENT_TIMESTAMP), CURRENT_TIMESTAMP), CURRENT_TIMESTAMP) IN (0,6)
THEN 5
ELSE DATEDIFF(DAY, DATEADD(DAY, 1-DATEPART(WEEKDAY, CURRENT_TIMESTAMP), CURRENT_TIMESTAMP), CURRENT_TIMESTAMP)
END
which works but is a bit messy and i am interested to see if there is a better solution to this.
Here's one way, borrowed from Jeff Moden via SQLServerCentral. (I'd comment this reply, but I don't have enough whacky points :( )
--count weekdays between two dates
DECLARE #StartDate DATETIME = '2019-11-01'
DECLARE #EndDate DATETIME = '2019-11-30'
SELECT (DATEDIFF(DD, #StartDate, #EndDate) + 1) --Total days in period, including weekends
-(DATEDIFF(WK, #StartDate, #EndDate) * 2) --minus number of whole weekends in the period * 2 days
-(CASE WHEN DATENAME(DW, #StartDate) = 'Sunday' THEN 1 ELSE 0 END) --minus 1 if the period starts on a Sunday
-(CASE WHEN DATENAME(DW, #EndDate) = 'Saturday' THEN 1 ELSE 0 END) --minus 1 if the period ends on a Saturday
Of course, there are issues here, such as the use of English day names that won't travel well, but those can be worked around if necessary.
I have variation of this built into a "WeekdayCount" function that comes in very handy!
Way more detail here: https://www.sqlservercentral.com/articles/calculating-work-days
additional solution to already posted by #tim-monfries:
DECLARE #StartDate DATETIME = '2019-11-01';
DECLARE #EndDate DATETIME = '2019-11-30';
WITH cte AS
(
SELECT #StartDate AS SomeDate
UNION ALL
SELECT SomeDate+1 FROM cte WHERE SomeDate < #EndDate
)
SELECT COUNT(*)
FROM cte
WHERE DATENAME(dw, SomeDate) NOT IN ('Sunday', 'Saturday');
I'm looking to create a Case statement so that,
If the current time is before 11AM, I want the information from yesterday as well as today.
If the time is after 11AM, I only want the information from today.
Here's what I have right now
FROM [EDC].[dbo].[DIM_DefectData] with (NoLock)
Where
Case
When datepart(hh, GetDate()) < 11 then
[InitiateDt] > DATEADD(day, DATEDIFF(day, 0, GETDATE()),-1)
Else
[InitiateDt] > DATEADD(day, DATEDIFF(day, 0, GETDATE()),0)
End
And ....(additional requirements which are working)
If I understand your problem correctly, the following is you want:
FROM [EDC].[dbo].[DIM_DefectData] WITH (NOLOCK)
WHERE [InitiateDt] > (
CASE
WHEN DATEPART(HH, GETDATE()) < 11
THEN DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), -1)
ELSE DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)
END )
I placed the [InitiateDt] near by the WHERE clause.
try this
select * from yourTable
where [InitiateDt] > Case When datepart(hh,getdate()) <11
Then dateadd(day,datediff(day,0,getdate()),-1)
Else dateadd(day,datediff(day,0,getdate()),0)
END
Try this:
DECLARE #t table(d datetime)
insert #t values
('2016-08-30 09:00'),
('2016-08-30 10:00'),
('2016-08-31 10:00'),
('2016-08-30 11:00'),
('2016-08-30 11:08')
if(DATEPART(HH, GETDATE()) < 11)
SELECT CAST(d AS TIME) FROM #t
WHERE CAST(d AS TIME) <= CAST('11:00' AS TIME)
ELSE
SELECT CAST(d AS TIME) FROM #t
WHERE CAST(d AS TIME) > CAST('11:00' AS TIME)
The above returns all today's data as well yesterday before 11:00AM.
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
hi i want to find the total days of two month and split the days for month wise..for example...
26-02-2013 to 3-3-2013
here for the february month it shows 2days leave but march month i wont display the total leave..this is my query..can anyone correct my query..it shows only febraury days only,,march days is not shown here..
SELECT month(fdate) as Month_Number
, datename(month, fdate) as Month
, case when month(fdate) <> month(tdate) then
datediff(day, fdate, DATEADD(month, ((YEAR(fdate) - 1900) * 12) + MONTH(fdate), -1))
else
datediff(day, fdate, tdate)
end as Leaves
from test
where empid like '112'
Try this, it will display the number of days for each month:
SELECT *
, DATEADD(DAY, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, t.fdate) + 1, 0)) Last_In_Month_Of_Beginning
, DATEADD(MONTH, DATEDIFF(MONTH, 0, t.tdate), 0) First_In_Month_Of_End
INTO #temp1
FROM test t
WHERE empid LIKE '112'
SELECT number Month_Number
, CASE
WHEN MONTH(fdate) = MONTH(tdate) THEN DATEDIFF(DAY, fdate, tdate) - 1
WHEN MONTH(Last_In_Month_Of_Beginning) = number THEN DATEDIFF(DAY, fdate, Last_In_Month_Of_Beginning)
WHEN MONTH(First_In_Month_Of_End) = number THEN DATEDIFF(DAY, First_In_Month_Of_End, tdate)
END Leave
INTO #temp2
FROM #temp1 a
JOIN master..spt_values v ON
v.type = 'P'
AND v.number BETWEEN MONTH(a.Last_In_Month_Of_Beginning) AND MONTH(a.First_In_Month_Of_End)
SELECT Month_Number
, SUM(Leave) Leaves
FROM #temp2
GROUP BY Month_Number
Here is an SQL Fiddle