How to query from the result of a changed column of a table in postgresql - postgresql

So I have a string time column in a table and now I want to change that time to date time type and then query data for selected dates.
Is there a direct way to do so? One way I could think of is
1) add a new column
2) insert values into it with converted date
3) Query using the new column
Here I am stuck with the 2nd step with INSERT so need help with that
ALTER TABLE "nds".”unacast_sample_august_2018"
ADD COLUMN new_date timestamp
-- Need correction in select statement that I don't understand
INSERT INTO "nds".”unacast_sample_august_2018” (new_date)
(SELECT new_date from_iso8601_date(substr(timestamp,1,10))
Could some one help me with correction and if possible a better way of doing it?
Tried other way to do in single step but gives error as Column does not exist new_date
SELECT *
FROM (SELECT from_iso8601_date(substr(timestamp,1,10)) FROM "db_name"."table_name") AS new_date
WHERE new_date > from_iso8601('2018-08-26') limit 10;
AND
SELECT new_date = (SELECT from_iso8601_date(substr(timestamp,1,10)))
FROM "db_name"."table_name"
WHERE new_date > from_iso8601('2018-08-26') limit 10;
Could someone correct these queries?

You don't need those steps, just use USING CAST clause on your ALTER TABLE:
CREATE TABLE foobar (my_timestamp) AS
VALUES ('2018-09-20 00:00:00');
ALTER TABLE foobar
ALTER COLUMN my_timestamp TYPE timestamp USING CAST(my_timestamp AS TIMESTAMP);
If your string timestamps are in a correct format this should be enough.

Solved as follows:
select *
from
(
SELECT from_iso8601_date(substr(timestamp,1,10)) as day,*
FROM "db"."table"
)
WHERE day > date_parse('2018-08-26', '%Y-%m-%d')
limit 10

Related

PostgreSQL transforming the entire column value in a table

I have been trying to change all the values in a column. When I do it turns out to take my table and drop all the rows that match my criteria in the where clause.
Example
|_Month_|_Cost_|_Title_|
|___2___|_15.99|_hello_|
|___2___|_32.87|_John__|
|___2___|_32.87|_Neat__|
|___3___|_32.87|_Kelps_|
|___4___|_32.87|_Gulp__|
|___5___|_32.87|_Tried_|
I run this Query
UPDATE tableName SET Month = 'FEB' WHERE Month = 2;
The Change:
|_Month_|_Cost_|_Title_|
|__FEB__|_32.87|_Neat__|
|___3___|_32.87|_Kelps_|
|___4___|_32.87|_Gulp__|
|___5___|_32.87|_Tried_|
What I need:
|_Month_|_Cost_|_Title_|
|__FEB__|_15.99|_hello_|
|__FEB__|_32.87|_John__|
|__FEB__|_32.87|_Neat__|
|___3___|_32.87|_Kelps_|
|___4___|_32.87|_Gulp__|
|___5___|_32.87|_Tried_|
Where am I going wrong?
I have also tried to get the date changed from a timestamp with
SELECT TO_DATE(payment_timestamp, 'Mon") payment_month
from tablename;
but PostgreSQL doesn't recognize the TO_DATE()?? Can someone tell me why?

Postgres timestamp equality

I have a table with just two columns:
ts::timestamptz (unique),
values::jsonb
I need to find a row with specific ts, but no matter how I cast and convert things around, it just does not work. E.g.
select t.ts::timestamp from table t limit 1 ... returns 2020-03-16 12:46:02
this query
to_timestamp('2020-03-16 12:46:02','YYYY-MM-DD HH24:MI:SS') ... returns 2020-03-16 12:46:02
but query
select * from table t where t.ts::timestamp = to_timestamp('2020-03-16 12:46:02','YYYY-MM-DD HH24:MI:SS')
returns nothing. Now apparently I'm doing a rookie mistake somewhere, but I just can't see it.

Redshift: milliseconds to timestamp

Let us say we have have two tables:
CREATE TABLE IF NOT EXISTS tech_time(
ms_since_epoch BIGINT
);
CREATE TABLE IF NOT EXISTS readable_time(
ts timestamp without time zone,
);
Let us say tech_time has data and we would like to populate readable_time.
So in Postgres you could use to_timestamp(double precision) and do something like
INSERT INTO readable_time(ts)
SELECT DISTINCT to_timestamp(ms_since_epoch::float / 1000) AS ts,
FROM tech_time;
No such function seems to exist in Amazon Redshift:
function to_timestamp(double precision) does not exist
My question is: how do I properly populate readable_time, while losing the least amount of precision?
We can try using DATEADD and add the ms_since_epoch to January 1, 1970:
INSERT INTO readable_time (ts)
SELECT DATEADD(ms, ms_since_epoch, 'epoch')
FROM tech_time;

Postgres query for report

I'm trying to solve this problem:
I have a query/view that will join ~10 tables to extract some fields for a report (if any). The query doesn't use any grouping function, only joins and cut off some unuseful data.
I have to take this one big view, get the group for the first index, take the max of a date in the second column and take all the information from other fields referring the record of the max value.
I cannot be able to to this in postgres.
As a pseudo code I can give this:
select 1
, max(2)
, 3 referred to the record from max(2)
, 4 referred to the record from max(2)
, ...
, 20 referred to the record from max(2)
from (ViewWithAllJoins) a
group by 1
For privacy and business problem I had to obfuscate some informations, 1/2/3/4... are the name of the column from the view "ViewWithAllJoins", I hope that the problem is still understandable and resolvable!
I've tryied with WINDOW command as reported in Convert keep dense_rank from Oracle query into postgres but I cannot be able to use the group by that I need. Other tryes that I've done was about the dense_rank like shown in Dense_rank first Oracle to Postgresql convert but I can't do any assumption on the order of the data in any of the other fields in exception of 1 and 2, so I can't use any of the aggregate function on them.
Any ideas? Possibly without adding too much subqueryes.
Thank you!
EDIT:
As suggested I'll add some synthetic data to better understand the problem and what I want.
Start:
ID DATE COLUMN1 COLUMN2 COLUMN3
=====================================================================
88888888;"2016-04-02 09:00:00";"aaaaaaaaaaa";"TEXT89" ; 999999999
88888888;"2018-08-21 09:00:00";"a" ;"TEXT1" ; 988888888
88888888;"2017-11-09 09:00:00";"zzzz" ;"TEXT80000" ; 850580582
75858585;"2017-01-31 09:00:00";"~~~~~~~~~~~";"TEXT10" ; 101010101
75858585;"2018-04-02 09:00:00";"eeeeeeeeeee";"TEXT1000" ; 111111111
99999999;"2016-04-02 09:00:00";"8d2ecafd866";"TEXT808911"; 777777777
What I want:
ID DATE COLUMN1 COLUMN2 COLUMN3
===================================================================
88888888;"2018-08-21 09:00:00";"a" ;"TEXT1" ; 988888888
75858585;"2018-04-02 09:00:00";"eeeeeeeeeee";"TEXT1000" ; 111111111
99999999;"2016-04-02 09:00:00";"8d2ecafd866";"TEXT808911"; 777777777
So the group by id, the max of the date and the other fields related to the row of the max date.
-- So you have duplicate records per ID, and for every ID you want to select the record with the most recent date ?
Use NOT EXISTS:
SELECT id,zdate,column1,column2,column3 -- , ...
FROM queryview t
WHERE NOT EXISTS (
SELECT *
FROM queryview x
WHERE x.id=t.id
AND x.zdate > t.zdate
);
Or, use row_number() over a window, and pick only the row with the final date:
SELECT id,zdate,column1,column2,column3 -- , ...
FROM ( SELECT *
, row_number() OVER(PARTITION BY id, ORDER BY zdate DESC) AS rn
FROM queryview
) q
WHERE q.rn = 1
;

How toConvert minutes into hours in postgresql

I'm new in PostgreSQL I need to convert the minute's value in a column into hours and minutes format I have searched in various sources but failed to achive.Some one please help me to achieve this.
In mean while I try to use to_char() as follows :
UPDATE tablename SET col2 = TO_CHAR(((col1*60 ||`second`))::interval, ‘HH24:MI:SS’) where id = 145;
but I get the following error...
column "late_by" is of type timestamp with time zone but expression is of type text
LINE 2: UPDATE attendance SET late_by = TO_CHAR(((lateby*60 || 'seco...
^
HINT: You will need to rewrite or cast the expression.
It is unclear what type each column in your statement is.
But if it helps, you can perform maths on intervals
select interval '60 seconds' * 15;
or in your case, if "col1" is integer: interval '60 seconds' * col1;
your column late_by is of time timestamp, yet you want to update it with interval, not timestamp. If you want to save how much time somebody is late, better use interval, eg:
t=# create table w3 (t interval);
CREATE TABLE
t=# insert into w3 select (185||' seconds')::interval;
INSERT 0 1
t=# select * from w3;
t
----------
00:03:05
(1 row)
as you can see "conversion" to minutes done by postgres itself