I want to run a simple T-SQL SELECT query such that this input (datetimeoffset)...
2015-01-01 00:15:00.0000000 +01:00
OR
2015-05-04 14:15:00.0000000 +02:00
...comes out as this output (datetime):
2015-01-01 01:15:00
OR
2015-05-04 16:15:00
Input is one column and output should also be one column.
Any ideas?
UPDATE 20170126
Ok as always it is never as easy as I think. The query is part of a bigger query, which I have now formulated as follows (see below), the input column being named 'TimeStamp' and the output column being named 'Tijd'. This doesn't work though as it doesn't seem to recognize [TimeStamp] in the declaration of the variable. What am I missing?
DECLARE #dt datetimeoffset = (SELECT CONVERT(datetimeoffset, [TimeStamp]))
SELECT #dt as Original
,CONVERT(datetime2,#dt,1) AS Tijd
,[Id]
,[EanCode]
,[DataAccessPointId]
,[DataSource]
,[ElectricityUsageNormalkWh] AS Piek
,[ElectricityUsageLowkWh] AS Dal
,[DateAltKey] = CONVERT(int, CONVERT(varchar(8), [TimeStamp], 112))
,[TimeAltKey] = DATEPART(hh,[TimeStamp]) * 10000 + DATEPART(mi,[TimeStamp]) * 100 + DATEPART(ss,[TimeStamp])
FROM [dbo].[ElectricityTelemetryData]
I think you have your time offset logic the wrong way around in your question regarding your +/- values, but you have a couple options depending on the data type you want as output:
declare #dt datetimeoffset = (select convert(datetimeoffset,'2015-01-01 00:15:00.0000000 +01:00'))
select #dt as Original
,convert(datetime2,#dt,1) as Converted
,switchoffset(#dt,'+00:00') as Switched
Output:
Original | Converted | Switched
2015-01-01 00:15:00.0000000 +01:00 | 2014-12-31 23:15:00.0000000 | 2014-12-31 23:15:00.0000000 +00:00
Related
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);
I would like to take a string in the format 'YYYYQQ' and parse it into a date. Specifically I would like to parse it into the first date of the quarter. For example I would like to parse '2016Q2' into '2016-04-01'.
Per the Postgres documentation, "Q (quarter) is ignored by to_date and to_timestamp". Well frankly I wish it wasn't ignored :) This means this code will return a result I don't want:
select to_date('2014q3', 'YYYY\qQ');
**result**
2014-01-01
**desired result**
2014-07-01
How could I parse this string to the proper date?
Use string manipulation functions format(), left() and right():
with quarters(q) as (
values ('2014q1'), ('2015q2'), ('2016q3'), ('2017q4')
)
select format('%s-%s-1', left(q, 4), right(q, 1)::int* 3- 2)::date
from quarters;
format
------------
2014-01-01
2015-04-01
2016-07-01
2017-10-01
(4 rows)
Create a function for convenience:
create or replace function quarter_to_date(text)
returns date language sql as $$
select format('%s-%s-1', left($1, 4), right($1, 1)::int* 3- 2)::date
$$;
with quarters(q) as (
values ('2014q1'), ('2015q2'), ('2016q3'), ('2017q4')
)
select quarter_to_date(q)
from quarters;
quarter_to_date
-----------------
2014-01-01
2015-04-01
2016-07-01
2017-10-01
(4 rows)
In PostgreSQL 9.4 and greater there is a function that will create a date.
make_date(year, month, day)
You can use it as follows:
make_date(year, quarter * 3 -2 , 1)::date
My first query is:
SELECT distinct wfc_request_job_id,wfc_request_job_info,
replace(iso_cc,';',' ') as "iso_cc",to_char(wfc_request_start_ts,'yyyy-MM-dd HH:mm:ss') as ts,
sent_message_count,
(link_object_count + poi_object_count + point_address_object_count) as request_object_count
FROM wfc_request_job
where
wfc_request_job_id=173526;
This returns ts as 2015-08-16 03:08:59
Second Query:
SELECT wfc_request_job_id,wfc_request_start_ts,wfc_request_end_ts,replace(iso_cc,';',' ') as "iso_ccs",sent_message_count,wfc_queue_name
FROM wfc_request_job
where
to_char(wfc_request_start_ts,'YYYY-MM-DD') >= to_char(to_date('08/16/2015','MM/DD/YYYY'),'YYYY-MM-DD')
and to_char(wfc_request_start_ts,'YYYY-MM-DD') <= to_char(to_date('08/16/2015','MM/DD/YYYY'),'YYYY-MM-DD')
order by wfc_request_job_id desc
This returns ts of the job id mentioned above as - "2015-08-16 15:58:59.809+02"
How can I make both the queries return ts in UTC+02 - i.e. same timezone
The data type of wfc_request_start_ts is - timestamp with timezone
I changed to queries to have the format HH24:MI:SS however that did not help. Please note that the webapp using these queries will be opened in both Germany and USA.
According to postgresql manual to_char there is TZ (and OF as of v9.4) template patterns for Date/Time formatting.
Therefore in query you need to add it so
postgres=# select to_char(now(),'yyyy-MM-dd HH24:mm:ss TZ');
to_char
------------------------
2015-08-19 12:08:56 CEST
(1 row)
Also, make sure you specify timezone when converting
so instead
to_date('08/16/2015','MM/DD/YYYY')
use
TIMESTAMP WITH TIME ZONE '2015-08-16 00:00:00+02';
in second query.
So in my database i have a table with startimestamp that is "Timestamp with time zone" type
but what i want to display the timestamp without the time zone so i thought this would work
Select to_char("StartTimestamp",'YYYY/MM/DD HH24:MM:SS')from "Samples" where "ID" = 20
and a i get
"2013/08/02 14:08:04"
but the when i do it without the to_char and just call the timestamp for the same id like this
select "StartTimestamp" from "Samples" where "ID"=20
i get this which is the correct one
"2013-08-02 14:31:04-07"
I'm i missing something the to_char statement? Thanks
Change MM to MI in the minutes place
select
to_char(now(),'YYYY/MM/DD HH24:MM:SS'),
to_char(now(),'YYYY/MM/DD HH24:MI:SS');
to_char | to_char
---------------------+---------------------
2013/08/21 15:08:00 | 2013/08/21 15:51:00
I have a simple question regarding T-SQL. I have a stored procedure which calls a Function which returns a date. I want to use an IF condition to compare todays date with the Functions returned date. IF true to return data.
Any ideas on the best way to handle this. I am learning t-sql at the moment and I am more familar with logical conditions from using C#.
ALTER FUNCTION [dbo].[monday_new_period](#p_date as datetime) -- Parameter to find current date
RETURNS datetime
BEGIN
-- 1 find the year and period given the current date
-- create parameters to store period and year of given date
declare #p_date_period int, #p_date_period_year int
-- assign the values to the period and year parameters
select
#p_date_period=period,
#p_date_period_year = [year]
from client_week_uk where #p_date between start_dt and end_dt
-- 2 determine the first monday given the period and year, by adding days to the first day of the period
-- this only works on the assumption a period lasts a least one week
-- create parameter to store the first day of the period
declare #p_start_date_for_period_x datetime
select #p_start_date_for_period_x = min(start_dt)
from client_week_uk where period = #p_date_period and [year] = #p_date_period_year
-- create parameter to store result
declare #p_result datetime
-- add x days to the first day to get a monday
select #p_result = dateadd(d,
case datename(dw, #p_start_date_for_period_x)
when 'Monday' then 0
when 'Tuesday' then 6
when 'Wednesday' then 5
when 'Thursday' then 4
when 'Friday' then 3
when 'Saturday' then 2
when 'Sunday' then 1 end,
#p_start_date_for_period_x)
Return #p_result
END
ALTER PROCEDURE [dbo].[usp_data_to_retrieve]
-- Add the parameters for the stored procedure here
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
IF monday_new_period(dbo.trimdate(getutcdate()) = getutcdate()
BEGIN
-- SQL GOES HERE --
END
Thanks!!
I assume you are working on Sql2008. See documentation of IF and CASE keywords for more details.
CREATE FUNCTION dbo.GetSomeDate()
RETURNS datetime
AS
BEGIN
RETURN '2012-03-05 13:12:14'
END
GO
IF CAST(GETDATE() AS DATE) = CAST(dbo.GetSomeDate() AS DATE)
BEGIN
PRINT 'The same date'
END
ELSE
BEGIN
PRINT 'Different dates'
END
-- in the select query
SELECT CASE WHEN CAST(GETDATE() AS DATE) = CAST(dbo.GetSomeDate() AS DATE) THEN 1 ELSE 0 END AS IsTheSame
This is the basic syntax for a T-SQL IF and a date compare.
If you are comparing just the date portion for equality you will need to use:
select dateadd(dd,0, datediff(dd,0, getDate()))
This snippet will effectively set the time portion to 00:00:00 so you can compare just dates. So in use it will look something like this.
IF dateadd(dd,0, datediff(dd,0, fn_yourFunction())) = dateadd(dd,0, datediff(dd,0, GETDATE()))
BEGIN
RETURN SELECT * FROM SOMEDATA
END
Hope that helps!