RedShift: How to cast integer with year into a date? - postgresql

Assume a user tries to cast a number (year of birth) into a date.
select year_of_birth, cast(year_of_birth as date) from visit_occurrence
And gets this error :
cannot cast type smallint to date
What is the proper way?
e.g., cast(cast(YOB as string)+'-01-01' as date) does not work either.

use
select year_of_birth, to_date(cast(year_of_birth as text), 'YYYY') from visit_occurrence ;

Related

TIMESTAMP- creation_date :: date between '2022-05-15' and '2022-06-15'

I just wanted to know the difference between these two codes:
select count (user_id) from tb_users where
creation_date :: date between '2022-05-15' and '2022-06-15'
Result: 41,232
select count (user_id) from tb_users where
creation_date between '2022-05-15' and '2022-06-15'
Result: 40,130
As far as I see, it is related with the timestamp, but I do not understand the difference.
Thank you!
Your column creation_date in the table is most probably in timestamp format, which is '2022-05-15 00:00:00'. By adding ::date <- you are casting your timestamp format to date format: '2022-05-15'.
You can read more about casting data types here:
https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-cast/
When you ask Postgres to implicitly coerce a DATE value to a TIMESTAMP value - the hours, minutes and seconds are set to zero.
In the first query, you explicitly cast the creation date to DATE which is successfully compared to the provided DATE values.
In the second query, the creation date is of type TIMESTAMP and so PostgreSQL converts your DATE values to TIMESTAMP values and the comparison becomes
creation_date >= '2022-05-15 00:00:00' AND creation_date <= '2022-06-15 00:00:00'
Obviously, this produces different resultset than the first query.

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;

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

text to timestamp in postgresql

In the view I have a text column which contains a timestamp in this format '20/03/2018 00:00' and I'm trying to make a selection with a between clause but it's not working
SELECT id,entry_date
FROM v_view
WHERE entrada BETWEEN to_timestamp('20/03/2018 00:00','DD/MM/YYYY')::timestamp and to_timestamp('22/03/2018 00:00')::timestamp
order entry_date
with this error message
ERROR: el operador no existe: text >= timestamp without time zone
LINE 3: WHERE entry_date BETWEEN to_timestamp('20/03/2018 00:00','DD/MM.
you need to convert the entrada column value to a timestamp.
Also: casting the result of to_timestamp() to a timestamp is useless because to_timestamp() already returns a timestamp
SELECT id,entry_date
FROM v_view
WHERE to_timestamp(entrada, 'dd/mm/yyyy hh24:mi')
BETWEEN to_timestamp('20/03/2018', 'DD/MM/YYYY')
and to_timestamp('22/03/2018', 'dd/mm/yyyy')
order entry_date;
I prefer to use ANSI SQL timestamp literals over the to_timestamp function:
SELECT id,entry_date
FROM v_view
WHERE to_timestamp(entrada, 'dd/mm/yyyy hh24:mi')
BETWEEN timestamp '2018-03-20 00:00:00'
and timestamp '2018-03-22 00:00:00'
order entry_date
Do not store date, time or timestamp values in a text or varchar column. You should define that column as timestamp then you don't need to convert anything and you don't need to deal with invalid timestamp values in that column.

TSQL DateTime Comparison

What I am trying to do is get a result from sql where the dates are in a certain range but its not working correctly, here is my query.
DECLARE #CurrDate DATETIME
SET #CurrDate = GETDATE()
SELECT dbo.ProductDetails.PartnerID
,dbo.ProductDetails.ProductID
,dbo.Products.ProductName
,StartDate
,EndDate
FROM dbo.ProductDetails
INNER JOIN dbo.Products
ON dbo.ProductDetails.ProductID = dbo.Products.ProductID
WHERE CONVERT(VARCHAR(10),StartDate,111) <= #CurrDate
AND CONVERT(VARCHAR(10),EndDate, 111) >= #CurrDate
but when the Enddate = #CurrDate the row does not show, but if i make that date just one day higher it gets displayed. Am i doing anything wrong? Any advice will do, thanks.
GetDate() returns date and time, while your conversion to varchar strips away the time part (I'm suspecting that's all it's actually supposed to do). So you would need to do the same conversion for #CurrDate.
If what you want is to simply consider the date only (ignoring the time part), you could use DATEDIFF instead of converting to varchar (see here); example:
DECLARE #CurrDate DATETIME
SET #CurrDate = GETDATE()
SELECT dbo.ProductDetails.PartnerID, dbo.ProductDetails.ProductID,
dbo.Products.ProductName , StartDate, EndDate
FROM dbo.ProductDetails INNER JOIN
dbo.Products ON dbo.ProductDetails.ProductID = dbo.Products.ProductID
-- where StartDate is on the same day or before CurrDate:
WHERE DATEDIFF(day, StartDate, #CurrDate) >= 0 AND
-- and where EndDate is on the same day or after CurrDate:
DATEDIFF(day, EndDate, #CurrDate) <= 0
If you want only DATE comparison, without time use the
cast(CONVERT(varchar, StartDate, 112) as datetime)
I am quite sure that the comparison takes into account the time as well as the date, in which case if the dates are the same but the current time is greater than the time being compared to you won't get that row as a result.
So, what you need to do is just extract the date part and compare those.
GETDATE() gives you date and time
if yours column have only date
then
CONVERT(VARCHAR(10),StartDate,111) <= #CurrDate
can give you unexpected result
remember
19.12.2011 14:41 > 19.12.2011 00:00
If you are using SQL 2008 or later, and wanting to compare only the date, not the time, you can also do:
Cast(StartDate as Date)
(This avoids having to convert to a string.)