SQL Statement to Select Day Interval - sql-server

How can I get the range between a day dynamically for e.g. BETWEEN 23.05.2012 00:00 AND 23.05.2012 23:59 using MSSQL ? I got the first part;
WHERE
AND s.SCHEDULE_START_DATE BETWEEN dateadd(DAY, datediff(DAY, 0, getdate()), 0) AND FILL HERE

You will have to try something like
s.SCHEDULE_START_DATE >= dateadd(DAY, datediff(DAY, 0, getdate()), 0)
AND s.SCHEDULE_START_DATE < (dateadd(DAY, datediff(DAY, 0, getdate()), 0) + 1)
Have a look at the below example
SQL Fiddle DEMO

Try this one -
Query:
DECLARE #Dates TABLE
(
SCHEDULE_START_DATE DATETIME
)
INSERT INTO #Dates
VALUES
('20130522'),
('20130523'),
('20130524'),
('20130523 18:00:00'),
('20130523 23:59:59')
DECLARE
#DateFrom DATETIME = DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)
, #DateTo DATETIME = DATEADD(SECOND, 86399, DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0))
SELECT *
FROM #Dates
WHERE SCHEDULE_START_DATE BETWEEN #DateFrom AND #DateTo
Output:
SCHEDULE_START_DATE
-----------------------
2013-05-23 00:00:00.000
2013-05-23 18:00:00.000
2013-05-23 23:59:59.000

Related

How to get data of current date using sum in SQL?

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);

Where Statement with Case based on Current Time

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.

SQL Server - Date String

Can you please help me create an sql statement that will get the previous date and concatenate that date in this format:
'2016-05-05 00:00:00'
I already know the sql function to get the previous date but I don't know yet on how to get the time in the expected format. My query is something like this
Select *
from table
where
transaction_date between '2016-05-05 00:00:00' and '2016-05-05 23:59:59'
So I need 00:00:00 and 23:59:59 to be concatenated in the date.
You don't need the times at all. Just don't use BETWEEN and use >= and < for the next day, like this:
SELECT *
FROM table
WHERE transaction_date >= '2016-05-05'
AND transaction_date < '2016-05-06'
Or if you only have the single date value:
DECLARE #date DATETIME = '2016-05-05'
SELECT *
FROM table
WHERE transaction_date >= #date
AND transaction_date < DATEADD(DAY, 1, #date)
The added benefit of doing it this way is that you also don't miss out on times that occur in the last second of the day as your original query does. For example 2016-05-05 23:59:59.001
Edit: From the comments below
To get yesterdays date, get today's date and subtract a day from it:
DECLARE #date DATETIME = DATEADD(DAY, -1, CAST(GETDATE() AS DATE))
Now use the logic as mentioned above.
This function:
DATEADD(dd, DATEDIFF(dd, 0, GetDate()), 0)
...will turn 2016-05-05 18:18:231 into 2016-05-05 00:00:000. From there it is easy to get full date boundaries by adding and subtracting days:
DECLARE #Date DATETIME
,#YesterdayStartDate DATETIME
,#TodayStartDate DATETIME
SET #Date = GetDate()
SET #TodayStartDate = DATEADD(dd, DATEDIFF(dd, 0, #date), 0)
SET #YesterdayStartDate = DATEADD(dd, -1, #TodayStartDate)
SELECT #Date, #YesterdayStartDate, #TodayStartDate
SELECT *
FROM Table
WHERE
transaction_date >= #YesterdayStartDate AND
transaction_date < #TodayStartDate
This will give you the result with transaction_date on yesterday.
SELECT
*
FROM
TABLE
WHERE
transaction_date BETWEEN dateadd(DAY, datediff(DAY, 1, GETDATE()), 0) AND dateadd(DAY, 1, dateadd(DAY, datediff(DAY, 1, GETDATE()), 0))
Compare date with out time part . ie below code.
Select * from table
where CONVERT(VARCHAR(8), transaction_date , 112) = CONVERT(VARCHAR(8), getdate(), 112)

T-SQL statement for selecting all records on a future date

I need to select all records with a billing date 15 days from now.
This gives me nothing because it is trying to compare date and time:
"nextbill = dateadd(d, +15, getdate())"
This works:
"select *
from custrate
where nextbill >= '2014-01-02 00:00:00' and nextbill < '2014-01-02 23:59:59'"
How do I get everything with a date of 15 days from now ignoring the time?
I would use the start of the day with >= and start of the next day with a <...
declare #from datetime, #thru datetime;
set #from = dateadd(d, datediff(d, 0, getdate()) + 15, 0);
set #thru = dateadd(d, 1, #from);
select ...
from custrate
where nextbill >= #from and nextbill < #thru
select *
from custrate
where convert(date,nextbill) = DATEADD(d, 15, convert(date,getdate()))
or older versions of sql:
select *
from custrate
where DATEADD(dd, DATEDIFF(dd, 0, nextbill), 0) = DATEADD(dd, DATEDIFF(dd, 0, getdate()), 15)

Deterministic scalar function to get week of year for a date

Here is a great way of how to get day of week for a date, Deterministic scalar function to get day of week for a date.
Now, could anyone help me to create a deterministic scalar function to get week of year for a date please? Thanks.
This works deterministically, I can use it as a computed column.
datediff(week, dateadd(year, datediff(year, 0, #DateValue), 0), #DateValue) + 1
Test code:
;
with
Dates(DateValue) as
(
select cast('2000-01-01' as date)
union all
select dateadd(day, 1, DateValue) from Dates where DateValue < '2050-01-01'
)
select
year(DateValue) * 10000 + month(DateValue) * 100 + day(DateValue) as DateKey, DateValue,
datediff(day, dateadd(week, datediff(week, 0, DateValue), 0), DateValue) + 2 as DayOfWeek,
datediff(week, dateadd(month, datediff(month, 0, DateValue), 0), DateValue) + 1 as WeekOfMonth,
datediff(week, dateadd(year, datediff(year, 0, DateValue), 0), DateValue) + 1 as WeekOfYear
from Dates option (maxrecursion 0)

Resources