I can extract the month and day by using Day(Date()), Month(Date()). I can't extract hours, with HOUR(Date()). I get the following error.
'HOUR' is not a recognized built-in function name.
How can I extract hours?
SELECT DATEPART(HOUR, GETDATE());
DATEPART documentation
... you can use it on any granularity type i.e.:
DATEPART(YEAR, [date])
DATEPART(MONTH, [date])
DATEPART(DAY, [date])
DATEPART(HOUR, [date])
DATEPART(MINUTE, [date])
(note: I like the [ ] around the date reserved word though. Of course that's in case your column with timestamp is labeled "date")
Use datepart.
E.g.:
datepart(hh, date)
try this one too:
DATEPART(HOUR,GETDATE())
The DATEPART() function is used to return a single part of a date/time, such as year, month, day, hour, minute, etc.
datepart ***Abbreviation
year ***yy, yyyy
quarter ***qq, q
month ***mm, m
dayofyear ***dy, y
day ***dd, d
week ***wk, ww
weekday ***dw, w
hour ***hh
minute ***mi, n
second ***ss, s
millisecond ***ms
microsecond ***mcs
nanosecond ***ns
Example
select *
from table001
where datepart(hh,datetime) like 23
DATEPART(HOUR, [date]) returns the hour in military time ( 00 to 23 )
If you want 1AM, 3PM etc, you need to case it out:
SELECT Run_Time_Hour =
CASE DATEPART(HOUR, R.date_schedule)
WHEN 0 THEN '12AM'
WHEN 1 THEN '1AM'
WHEN 2 THEN '2AM'
WHEN 3 THEN '3AM'
WHEN 4 THEN '4AM'
WHEN 5 THEN '5AM'
WHEN 6 THEN '6AM'
WHEN 7 THEN '7AM'
WHEN 8 THEN '8AM'
WHEN 9 THEN '9AM'
WHEN 10 THEN '10AM'
WHEN 11 THEN '11AM'
WHEN 12 THEN '12PM'
ELSE CONVERT(varchar, DATEPART(HOUR, R.date_schedule)-12) + 'PM'
END
FROM
dbo.ARCHIVE_RUN_SCHEDULE R
Try this one too:
SELECT CONVERT(CHAR(8),GETDATE(),108)
select case when [am or _pm] ='PM' and datepart(HOUR,time_received)<>12
then dateadd(hour,12,time_received)
else time_received
END
from table
works
I can't extract hours, with HOUR(Date())
There is a way to call HOUR (I would not recommend to use it though because there is DATEPART function) using ODBC Scalar Functions:
SELECT {fn HOUR(GETDATE())} AS hour
LiveDemo
To include AM / PM - use the below:
SELECT
concat(case when datepart(hour,getdate()) % 12 = 0 then 12
else datepart(hour,getdate()) % 12 end,
case when datepart(hour,getdate()) < 12 then ' AM'
else ' PM' end
)
select convert(time,GETDATE())
you must use datepart()
like
datepart(hour , getdate())
Related
I'm trying to SELECT all the rows from a SQL database which are between an hour interval, for every day.
The datetime column is called "Dt" and has the following datetime format: 2019-10-17 16:03:43
I'd like to extract all the rows from this table where the Dt was between 22:00:00 and 02:00:00, for everyday.
SELECT *
FROM MY_TABLE
WHERE "Dt" BETWEEN '*-*- 22:00:00' AND '*-*- 02:00:00';
where * should be any...
Thanks for your support!
EDIT: I forgot to mention: I'm using the integrated SQL interpreter from DB Browser for SQLite
You need to extract the time part of the date and compare that it is within the range. Since midnight is between 22 and 2, you will need to split it to two comparisons, time between 22 and 0 and between 0 and 2.
To see how to extract the time take a look at this question.
With Postgres, assuming dt is defined as timestamp you can do the following:
SELECT *
FROM MY_TABLE
WHERE "Dt" BETWEEN "Dt"::date + time '22:00:00' and ("Dt"::date + 1) + time '02:00:00'
Or if you want to exclude timestamps at precisely 02:00:00
SELECT *
FROM MY_TABLE
WHERE "Dt" >= "Dt"::date + time '22:00:00'
and "Dt" < ("Dt"::date + 1) + time '02:00:00'
select DT_time from (
select cast (substr(to_char(Dt,'dd-mm-yyyy HH:MM:SS'),12,2) as integer ) as DT_time from MY_TABLE )
where DT_time between 2 and 22;
between 22:00:00 and 02:00:00
means:
SELECT *
FROM MY_TABLE
WHERE
substr(Dt, 12) BETWEEN '22:00:00' AND '23:59:59'
OR
substr(Dt, 12) BETWEEN '00:00:00' AND '02:00:00'
This will work ::
SELECT *
FROM MY_TABLE
WHERE DATEPART(HOUR, Dt)>22
AND DATEPART(HOUR, Dt)<2
Update :
SELECT *
FROM MY_TABLE
WHERE Dt Between DATEADD (hour,22,DATEADD(day, DATEDIFF(day, 0, Dt), 0)) AND DATEADD (hour,2,DATEADD(day, DATEDIFF(day, -1, Dt), 0))
SELECT *
FROM MY_TABLE
WHERE DATEPART(HOUR, Dt)>22
OR DATEPART(HOUR, Dt)<2
Above query work for you..
1st one will check only for particular date and consecutive next date along with your time range.
But If you don't care about dates and only looking for time interval in particular hours then 2nd one is for you.
For SQLite :
SELECT *
FROM MY_TABLE
WHERE strftime('%H','Dt')>22
OR strftime('%H','Dt')<2
I have a select, and I need to limit data only for two last days. So today is 24th Aug 2016 so I need to get data for 24th Aug 2016, 23th Aug 2016 and 22th Aug 2016. How can I do that? I suppose I should use DATEADD function, or something similar. It needs to be done dynamicaly.
I need to get something like this:
SELECT * FROM TABLE_NAME WHERE
DATE = '2016-08-22'
The date must be updated each day
DateAdd, exactly
SELECT * FROM TABLE_NAME
WHERE DATE BETWEEN dateadd(d,-2,cast(getDate() as date)) AND cast(getDate() as date)
SELECT *
FROM TABLE_NAME
WHERE cast(DATE as date) BETWEEN cast(DATEADD(D, -2, GETDATE()) as date) AND cast(GETDATE() as date)
SELECT * FROM TABLE_NAME WHERE
cast(DATE as date) >= cast(GETDATE()-2 as date)
or
--For limiting future dates
SELECT * FROM TABLE_NAME
WHERE
cast(DATE as date) in (cast(GETDATE()-2 as date),cast(GETDATE()-1 as date), cast(GETDATE() as date))
Use GETDATE() function
If there are future dates in this table you can perhaps use this
select * from table_name
where date <= getdate()
and date >= dateadd(day,-2,getdate())
SELECT * FROM TABLE_NAME WHERE
DATE >=cast(getdate()-2 as date)--so this will be rounded off to midnight and it is sargable
First you have to make today's date in absolute by converting it in float then floor and then convert it into small date time. And then using dateadd subtract 2 days from today's absolute date.
SELECT * FROM
TABLE_NAME
WHERE
DATE >= (SELECT DATEADD(dd,-2,CAST(FLOOR(CAST(GETDATE() as FLOAT)) as SMALLDATETIME)))
I am trying to group the number of hours that employees worked for the last 4 weeks but I want to group them on a weekly basis. For example:
WEEK HOURS
Feb 24 to March 2 55
March 3 to March 9 40
March 10 to March 16 48
March 17 to March 23 37
This is what I have so far, please help. thanks
SET DATEFIRST 1
SELECT CAST(MIN( [DT]) AS VARCHAR(20))+' TO '+CAST (MAX([DT]) AS VARCHAR(20)) AS DATE,
SUM(HOURS) AS NUM_HRS
FROM MyTable
GROUP BY DATEPART(WEEK,[DT])
HAVING COUNT(DISTINCT[DT])=7
Create a Calendar auxilliary table, with Year, Month, Week, Date columns (you can also add holidays and other interesting stuff to it, it has many potential uses) and populate it for the period of interest.
After that, it's as easy as this:
SELECT sum(hours), cast(min(date) as varchar), cast(max(date) as varchar)
FROM Calendar c
LEFT OUTER JOIN MyTable h on h.Date = c.date
GROUP BY year, week
ORDER BY year, week
SET DATEFIRST 1
SELECT DATEPART(WEEK,DT) AS WEEK,
SUM(HOURS) AS NUM_HRS
FROM MyTable
WHERE DT >= DATEADD(WEEK, -4, GetDate()),
GROUP BY DATEPART(WEEK,[DT])
Try something like
SELECT
DATEADD(DD,
CONVERT(INT, (DATEDIFF(DD, '1/1/1900', t.DT)/7)) * 7,
'1/1/1900') [WeekBeginDate],
DATEADD(DD,
(CONVERT(INT, (DATEDIFF(DD, '1/1/1900', t.DT)/7)) * 7) + 6,
'1/1/1900') [WeekEndDate],
SUM(HOURS) AS NUM_HRS
FROM MyTable t
GROUP BY CONVERT(INT, DATEDIFF(DD, '1/1/1900', t.DT)/7)
Though this is the brute force trick, I think in your case it will work.
EDIT : Modified the query a little bit, the error was caused because of the order in which DATEDIFF calculates the difference.
Also here is a SQL FIDDLE with a working example.
EDIT 2 : Updated the Fiddle with the Date Format. To customize the date format, this article would help.
How can you get today's date and convert it to 01/mm /yyyy format and get data from the table with delivery month 3 months ago? Table already contains delivery month as 01/mm/yyyy.
SELECT *
FROM TABLE_NAME
WHERE Date_Column >= DATEADD(MONTH, -3, GETDATE())
Mureinik's suggested method will return the same results, but doing it this way your query can benefit from any indexes on Date_Column.
or you can check against last 90 days.
SELECT *
FROM TABLE_NAME
WHERE Date_Column >= DATEADD(DAY, -90, GETDATE())
Latest Versions of mysql don't support DATEADD instead use the syntax
DATE_ADD(date,INTERVAL expr type)
To get the last 3 months data use,
DATE_ADD(NOW(),INTERVAL -90 DAY)
DATE_ADD(NOW(), INTERVAL -3 MONTH)
I'd use datediff, and not care about format conversions:
SELECT *
FROM mytable
WHERE DATEDIFF(MONTH, my_date_column, GETDATE()) <= 3
Last 3 months
SELECT DATEADD(dd,DATEDIFF(dd,0,DATEADD(mm,-3,GETDATE())),0)
Today
SELECT DATEADD(dd,DATEDIFF(dd,0,GETDATE()),0)
Last 3 months record
SELECT *, DATEDIFF(NOW(),`created_at`)as Datediff from `transactions` as t having Datediff <= 90
I have a tabel in a relation database which contains a lot of dates.
I my application logic I have divided one day into 4 parts of 6 hours each, starting at: 00:00, 06:00, 12:00 and 18:00.
Now I would like to find the time difference of the earliest record in the database for each quater of a day, and the beginning og the peiod. How can I do that?
In psuedo-sql i guess it looks like
select min(created_at - ROUND_DOWN_TO_6_HOURS(created_at)) from mytabel group by day_quater;
The problem is how to calculate "ROUND_DOWN_TO_6_HOURS". So if "created_at" is 19:15 it will be rounded down to 18:00 and "created_at - ROUND_DOWN_TO_6_HOURS(created_at)" will return 1:15 hourd
I'm working with psql
If you're just trying to locate the records that match these ranges, you could just use that in the WHERE clause like
select * from myTable
where datepart(hh, created_at) between 0 and 6
If your trying to create a computed field that will have the 00 or 06 ... then you could use the "DatePart()" function in sql to pull the hour... DATEPART ( hh, date )... This would return a numeric value of 0, 1, 2, 3, ... 23 and you can compute a field based on this value being between 2 of your hours listed...
Here's a sample...
select
case
when datepart(hh, add_dt) between 0 and 6 then 1
when datepart(hh, add_dt) between 7 and 12 then 2
when datepart(hh, add_dt) between 13 and 18 then 3
when datepart(hh, add_dt) between 19 and 24 then 4
end
from myTable
where add_dt is not null
You could use CASE in conjunction with your date column and datetime functions to establish the quarter-of-day (1,2,3,4) and extract the day part from the datetime value, group by day, quarter, and then use the MIN(yourdatecolumn) to grab the earliest time within each quarter grouping.
Not sure what you mean by "beginning of the period". but you can measure the difference between any arbitrary datetime and your set of earliest times per day-quarter which was instantiated in the manner above.
http://www.postgresql.org/docs/8.2/static/functions-datetime.html
select
record::time - (case
when record::time >= '18:00' then '18:00'
when record::time >= '12:00' then '12:00'
when record::time >= '6:00' then '6:00'
else '0:00' end
)::time as difference
from my_table
My PostgreSQL is a little rusty, but something like this:
select
date_trunc('day',CreatedOn) [Day],
min(case when date_part('hour',TIMESTAMP CreatedOn) < 6 then '00:00'
when date_part('hour',TIMESTAMP CreatedOn) < 12 then '06:00'
when date_part('hour',TIMESTAMP CreatedOn) < 18 then '12:00'
else '18:00'
end) [Quarter]
from MyTable
group by date_trunc('day',CreatedOn)
order by date_trunc('day',CreatedOn)