Categorize data by time periods - sql

I am looking for a SQL statement to select all rows from the table with time periods like Today, Yesterday..etc. The table holds one datetime column.
Here result set should automatically populate results with pretty date (Today, yesterday,.. Last month, Older)and number of records on the periods,
Today -- 10
Yesterday -- 35

If you are looking to define the time periods, then use case. You don't really define the exact definitions, but something like this:
select (case when col >= convert(date, getdate()) then 'Today'
when col >= dateadd(day, -1, convert(date, getdate())) then 'Yesterday'
when col >= dateadd(day, -6, convert(date, getdate())) then datename(weekday, col)
when col >= dateadd(day, -13, convert(date, getdate())) then 'Last Week'
when col >= dateadd(day, -20, convert(date, getdate())) then 'Two Weeks Ago'
when col >= dateadd(day, -27, convert(date, getdate())) then 'Thre Weeks Ago'
else 'Older'
end)
Here is a db<>fiddle.

Related

SQL, get any data between two days and specific time

I am trying to get any data that is between that time range of two days ago until yesterday.
Example: Retrieve any data between 3 PM two days ago and yesterday 3 PM. This query should work on the daily basis.
I am thinking something like but just don't know where to insert the time
select * from dbo.table where system_date between getdate()-2 and getdate()-1
You can use CAST(CAST(GETDATE() AS date) AS datetime) to get the beginning of today's date, then use DATEADD to subtract 1 or 2 days, and add 15 hours.
I strongly suggest you use >= AND < on dates, rather than BETWEEN, otherwise you get "on the interval" issues.
SELECT t.*
FROM dbo.[table] t
WHERE t.system_date >= DATEADD(hour, 15, DATEADD(day, -2, CAST(CAST(GETDATE() AS date) AS datetime)))
AND t.system_date < DATEADD(hour, 15, DATEADD(day, -1, CAST(CAST(GETDATE() AS date) AS datetime)));
try this
select *
from dbo.table
where system_date between dateadd(day, datediff(day, 2, getdate()), '15:00:00') and dateadd(day, datediff(day, 1, getdate()), '15:00:00')
You should use DATEADD for subtracting dates. Your query will look like this.
select *
from table
where system_date between dateadd(day, -2, getdate()) and dateadd(day, -1, getdate())

SQL statement to select all rows from previous day with time

Need to select rows from the previous day but before 08:00 am.
(date >= dateadd(day,datediff(day,1,GETDATE()),0)
AND CONVERT(varchar, date,108) BETWEEN '00:00:00' AND '08:00:00')
return rows of from the previous day and before 08:00 am.
You can use:
where date >= dateadd(day, -1, convert(date, getdate())) and
date < dateadd(hour, -16, convert(date, getdate()))
This query is structured so it can make use of indexes.
You can also phrase this as:
where convert(date, [date]) = dateadd(day, -1, convert(date, getdate()) and
convert(time, [date]) <= '08:00:00'
This should also use indexes, because conversion to a date is perhaps the only function that does not prevent the use of an index.
You're on the right track. This does a BETWEEN check on the beginning of the day yesterday and the beginning of the day yesterday + 8 hours:
date BETWEEN dateadd(day,datediff(day,1,GETDATE()),0)
AND dateadd(hour, 8, dateadd(day,datediff(day,1,GETDATE()),0))

Sybase - Filter records with current date efficiently

I am trying to filter records based on current date (date part only) against a column "date_sent" which is a DateTime datatype. Though this can be written in multiple ways, I want to know which method will be the most efficient. The table has 11-12 millions of records ant any given time.
Let's say the current date is 16th April 2018
SELECT *
FROM TABLE_NAME
WHERE datepart(YEAR, date_sent) = 2018
AND datepart(MONTH,date_sent) = 4
AND datepart(DAY,date_sent) = 16;
SELECT *
FROM TABLE_NAME
WHERE convert(char(8), date_sent, 112) = convert(char(8), getdate(), 112);
Any other suggestions.
I would start with:
select *
from table_name
where date_sent >= dateadd(day, datediff(day, 0, getdate()), 0) and
date_sent < dateadd(day, 1 + datediff(day, 0, getdate()), 0)
The right hand side removes the time component of the current date. The comparisons should allow Sybase to still us an index on date_sent.
EDIT:
Perhaps Sybase doesn't permit 0 as a date value. You can also do:
select *
from table_name
where date_sent >= dateadd(day, datediff(day, cast('2000-01-01' as date), getdate()), cast('2000-01-01' as date)) and
date_sent < dateadd(day, 1 + datediff(day, cast('2000-01-01' as date), getdate()), cast('2000-01-01' as date))

Get data from last month in SQL Server

I checked Get the records of last month in SQL server and it did not work!
I try to get the records of last month based on my database table and column issue_date.
What's the SQL query to do this?
For clarification, today (27-April-18) I want to get all records from March-18.
I have the issue_date in the format that I convert to date but below code gives me all records from 01-March-2018 to and including today.
DATEPART(month, CONVERT (VARCHAR(11),DATEADD(day,wo_header.issue_date,`1971/12/31`),106)) = DATEPART(month, DATEADD(month, -1, getdate()))
To get firstDay and lastDay of previous month
DECLARE #FirstDayOfLastMonth DATETIME = CONVERT(DATE, DATEADD(d, -(DAY(DATEADD(m, -1, GETDATE() - 2))), DATEADD(m, -1, GETDATE() - 1))),
#LastDayOfLastMonth DATETIME = CONVERT(DATE, DATEADD(d, -(DAY(GETDATE())), GETDATE()))
SELECT #FirstDayOfLastMonth, #LastDayOfLastMonth
Your required Query
SELECT *
FROM TABLE
WHERE CAST(issue_date AS DATE) BETWEEN CONVERT(DATE, DATEADD(d, -(DAY(DATEADD(m, -1, GETDATE() - 2))), DATEADD(m, -1, GETDATE() - 1))) AND CONVERT(DATE, DATEADD(d, -(DAY(GETDATE())), GETDATE()))
Perhaps the easiest method is eomonth(). If there is no time component on issuedate:
where issuedate > eomonth(getdate(), -2) and
issuedate <= eomonth(getdate(), -1)
If there is a time component:
where issuedate >= dateadd(day, 1, cast(eomonth(getdate(), -2) as date)) and
issuedate < dateadd(day, 1, cast(eomonth(getdate(), -1) as date))
Without eomonth, I would do:
where issuedate < cast(dateadd(day, 1 - day(getdate()), getdate()) as date) and
issuedate >= dateadd(month, -1, cast(dateadd(day, 1 - day(getdate()), getdate()) as date))
The code I figured out is not pretty but it works. It first adds extra column with the month number to the SELECT portion of my code:
Month(CONVERT (VARCHAR(11),DATEADD(day,wo_header.closing_date,'1971/12/31'),106)) As Month
And than is used for WHERE statement:
Month(CONVERT (VARCHAR(11),DATEADD(day,wo_header.closing_date,'1971/12/31'),106)) = month(getdate())-1
So for anyone like me working in SQL report kind-of environment it should work.

Select every date where date is equal to today's date minus 1 day - Not working with dateadd on Month/year - T SQL

Like the title says, I am trying to build a query that selects all records from a database table where the date is equal to yesterdays date.
The date column in the table is however of the format datetime (with hours, minutes, seconds as well) so I do the select based on the dates year, month and day (times don't matter as long as the date is yesterday).
To achieve this I have build the following query:
SELECT
*
FROM
qryTouchBoekingen
WHERE
(DATEPART(yyyy, myDateTime) = DATEADD(dd, -1, Datepart(dd, GetDate()))
AND (DATEPART(mm, myDateTime) = DATEADD(dd, -1, Datepart(mm, GetDate()))
AND (DATEPART(dd, myDateTime) = DATEADD(dd, -1, Datepart(dd, GetDate())) )
ORDER BY
Starttijd ASC
Though this doesn't return any records. When I only use it on the day part of the myDateTime column then it works (but obviously also returns all other years and months with that specific date).
I also couldn't do it using:
SELECT
*
FROM
qryTouchBoekingen
WHERE
myDateTime = DATEADD(dd, -1, GetDate())
because this give errors on the time.
How about this much simpler version:
cast(myDateTime as date) = cast(dateadd(day, -1, getdate()) as date)
Or, even better:
(myDateTime >= cast(dateadd(day, -1, getdate()) as date) and
myDateTime < cast(getdate() as date)
)
This version is more explicit in its ability to take advantage of an index. (The first will also take advantage of an index on myDateTime, but that is an exception to the rule that functions preclude the use of indexes.)
Try this one.
You should count previous day before making datepart from it
Select * from qryTouchBoekingen
WHERE ( DATEPART(yyyy, myDateTime) = Datepart(dd, DATEADD(dd, -1, GetDate()))
AND (DATEPART(mm, myDateTime) = Datepart(mm, DATEADD(dd, -1, GetDate()))
AND (DATEPART(dd, myDateTime) = Datepart(dd, DATEADD(dd, -1, GetDate())) )
Order by Starttijd ASC
DOes this work:
Select
*
from
qryTouchBoekingen
WHERE
CAST( myDateTime AS DATE) = CAST(DATEADD(day, -1, GetDate()) AS DATE)
Order by
Starttijd ASC