How to get a datetime interval as seconds (int)? - tsql

I have a table containing some datetime columns, now I want to get the timespan/interval between two columns in seconds (as int):
declare #Sessions TABLE
(
[session_id] [int] not null,
[start] [datetime] not null,
[end] [datetime] not null
)
insert into #Sessions([session_id], [start], [end])
values (1, '01.04.2012 08:15:05', '01.04.2012 08:16:40');
select [session_id], [end]-[start] as 'duration'
from #Sessions
What I get is a datetime like interval type: eg. 1900-01-01 00:01:35.000.
What I want is the timespan in seconds: eg. 95s.
Parsing the String should not be an option as I suppose that there's an easy to use function for that - deeply hidden in the msdn documentation, which I haven't found yet.
So, how to get those time intervals as int in seconds?

Change last select as
select [session_id],datediff(ss,[start],[end]) as 'duration' from #Sessions
I have tried the same below using table instead of table variable:

Using DATEDIFF, you can get the difference between 2 dates down to whichever resolution you want
e.g.
SELECT DATEDIFF(ss, start, end)
FROM #Sessions

SELECT [session_id]
, DATEDIFF(second, [start] - [end]) as 'Duration'
FROM #Sessions
DATEDIFF (Transact-SQL)
Returns the count (signed integer) of the specified datepart boundaries crossed between the specified startdate and enddate.

Related

Postgresql interval to Integer

Currently I have a column call days and the values are 1 day, 2 days etc. I am trying to extract or keep only the numeric value.
Something like:
select
CAST(LEFT(days, CHARINDEX(' ', days)) as integer) as #days
from daily_table
You could first cast the string to an interval, then use extract():
select extract(day from days::interval) as "#days"
from daily_table;
You can use substring() function to get the numeric value and then cast to INTEGER
select cast(substring(days, 1, position('d' in days)-2) as INTEGER)
as "#days" from daily_table;

Recurring future date at every 3 month after create date in PostgreSQL

I am looking for a function in PostgreSQL which help me to generate recurring date after every 90 days from created date
for example: here is a demo table of mine.
id date name
1 "2020-09-08" "abc"
2 "2020-09-08" "xyz"
3 "2020-09-08" "def"
I need furure date like 2020-12-08, 2021-03-08, 2021-06-08, and so on
First it's important to note that, if you happen to have a date represented as text, then you can convert it to a date via:
SELECT TO_DATE('2017-01-03','YYYY-MM-DD');
So, if you happen to have a text as an input, then you will need to convert it to date. Next, you need to know that if you have a date, you can add days to it, like
SELECT CURRENT_DATE + INTERVAL '90 day';
Now, you need to understand that you can use dynamic variables, like:
select now() + interval '1 day' * 180;
Finally, you will need a temporary table to generate several values described as above. Read more here: How to return temp table result in postgresql function
Summary:
create a function
that generates a temporary table
where you insert as many records as you like
having the date shifted
and converting text to date if needed
You can create a function that returns a SETOF dates/timestamps. The below function takes 3 parameters: a timestamp, an interval, the num_of_periods desired. It returns num_of_periods + 1 timestamps, as it returns the original timestamp and the num_of_periods each the specified interval apart.
create or replace
function generate_periodic_time_intervals
( start_date timestamp
, period_length interval
, num_of_periods integer
, out gen_timestamp timestamp
)
returns setof timestamp
language sql
immutable strict
as $$
select (start_date + n * period_length)::timestamp
from generate_series(0,num_of_periods) gs(n)
$$;
For your particular case to timestamp/date as necessary. The same function would work for your case with the interval specified as '3 months' or of '90 days'. Just a note the interval specified can be any valid INTERVAL data type. See here. It also demonstrates the difference between 3 months and 90 days.

Converting Integer values to Date in Presto SQL

Below is a script i am trying to run in Presto; Subtracting today's date from an integer field I am attempting to convert to date. To get the exacts days between. Unfortunately, it seems the highlighted block does not always convert the date correctly and my final answer is not correct. Please does anyone know another way around this or a standard method on presto of converting integer values to date.
Interger value in the column is in the format '20191123' for year-month-date
select ms, activ_dt, current_date, date_diff('day',act_dt,current_date) from
(
select ms,activ_dt, **CAST(parse_datetime(CAST(activ_dt AS varchar), 'YYYYMMDD') AS date) as act_dt**, nov19
from h.A_Subs_1 where msisdn_key=23480320012
) limit 19
You can convert "date as a number" (eg. 20180527 for May 27, 2018) using the following:
cast to varchar
parse_datetime with appropriate format
cast to date (since parse_datetime returns a timestamp)
Example:
presto> SELECT CAST(parse_datetime(CAST(20180527 AS varchar), 'yyyyMMdd') AS date);
_col0
------------
2018-05-27
You can use below sample query for your requirement:
select date_diff('day', date_parse('20191209', '%Y%m%d'), current_timestamp);

TSQL update Datetime with Random Value between 2 Dates

What's the easiest way to update a table that contains a DATETIME column on TSQL with RANDOM value between 2 dates?
I see various post related to that but their Random values are really sequential when you ORDER BY DATE after the update.
Assumptions
First assume that you have a database containing a table with a start datetime column and a end datetime column, which together define a datetime range:
CREATE DATABASE StackOverflow11387226;
GO
USE StackOverflow11387226;
GO
CREATE TABLE DateTimeRanges (
StartDateTime DATETIME NOT NULL,
EndDateTime DATETIME NOT NULL
);
GO
ALTER TABLE DateTimeRanges
ADD CONSTRAINT CK_PositiveRange CHECK (EndDateTime > StartDateTime);
And assume that the table contains some data:
INSERT INTO DateTimeRanges (
StartDateTime,
EndDateTime
)
VALUES
('2012-07-09 00:30', '2012-07-09 01:30'),
('2012-01-01 00:00', '2013-01-01 00:00'),
('1988-07-25 22:30', '2012-07-09 00:30');
GO
Method
The following SELECT statement returns the start datetime, the end datetime, and a pseudorandom datetime with minute precision greater than or equal to the start datetime and less than the second datetime:
SELECT
StartDateTime,
EndDateTime,
DATEADD(
MINUTE,
ABS(CHECKSUM(NEWID())) % DATEDIFF(MINUTE, StartDateTime, EndDateTime) + DATEDIFF(MINUTE, 0, StartDateTime),
0
) AS RandomDateTime
FROM DateTimeRanges;
Result
Because the NEWID() function is nondeterministic, this will return a different result set for every execution. Here is the result set I generated just now:
StartDateTime EndDateTime RandomDateTime
----------------------- ----------------------- -----------------------
2012-07-09 00:30:00.000 2012-07-09 01:30:00.000 2012-07-09 00:44:00.000
2012-01-01 00:00:00.000 2013-01-01 00:00:00.000 2012-09-08 20:41:00.000
1988-07-25 22:30:00.000 2012-07-09 00:30:00.000 1996-01-05 23:48:00.000
All the values in the column RandomDateTime lie between the values in columns StartDateTime and EndDateTime.
Explanation
This technique for generating random values is due to Jeff Moden. He wrote a great article on SQL Server Central about data generation. Read it for a more thorough explanation. Registration is required, but it's well worth it.
The idea is to generate a random offset from the start datetime, and add the offset to the start datetime to get a new datetime in between the start datetime and the end datetime.
The expression DATEDIFF(MINUTE, StartDateTime, EndDateTime) represents the total number of minutes between the start datetime and the end datetime. The offset must be less than or equal to this value.
The expression ABS(CHECKSUM(NEWID())) generates an independent random positive integer for every row. The expression can have any value from 0 to 2,147,483,647. This expression mod the first expression gives a valid offset in minutes.
The epxression DATEDIFF(MINUTE, 0, StartDateTime) represents the total number of minutes between the start datetime and a reference datetime of 0, which is shorthand for '1900-01-01 00:00:00.000'. The value of the reference datetime does not matter, but it matters that the same reference date is used in the whole expression. Add this to the offset to get the total number of minutes between the reference datetime.
The ecapsulating DATEADD function converts this to a datetime value by adding the number of minutes produced by the previous expression to the reference datetime.
You can use RAND for this:
select cast(cast(RAND()*100000 as int) as datetime)
from here
Sql-Fiddle looks quite good: http://sqlfiddle.com/#!3/b9e44/2/0

T-SQL How to update hour in a SmallDateTime column?

let's say that I have a SmallDateTime column in my table. How to update hours in each row in T-SQL ?
Get the target value's hour part.
Find the difference between the hour you want and the found hour.
Add the difference of hours to the target value.
The script:
UPDATE atable
SET datetimevalue = DATEADD(hour, #hour - DATEPART(hour, datetimevalue),
datetimevalue)
WHERE ...
UPDATE YourTable SET YourDateColumn = DateAdd(hh, 1, YourDateColumn)
will add 1 hour to the time value in YourDateColumn in every single row.
See this page for more info.
UPDATE YourTableName
SET YourSmallDateTimeColumn = DATEADD(HH, 1, YourSmallDateTimeColumn)
Will add any number of hours to your column. So if you get rid of the time component first:
SELECT CAST(CONVERT(char(8), YourSmallDateTimeColumn, 112) AS smalldatetime)
and add hour component to it later it should work.
From here
To add or subtract hours to a datetime
or smalldatetime value, you will use
the DATEADD date function. The
DATEADD date function returns a new
datetime value based on adding an
interval to the specified date. The
syntax of the DATEADD date function is
as follows:
DATEADD ( datepart , number, date )
datepart is the parameter that
specifies on which part of the date to
return a new value. For hours, you
can use either HOUR or HH. number is
the value used to increment datepart.
date is an expression that returns a
datetime or smalldatetime value, or a
character string in a date format.
Here's an example on how to use the
DATEADD date function to increase or
decrease a datetime value by a certain
number of hours:
SELECT DATEADD(HOUR, -12, GETDATE())AS [TwelveHoursAgo]
SELECT DATEADD(HH, 6, GETDATE()) AS [SixHoursLater]