How to extract Year and Month in SQL Postgres by using Data_Part function - postgresql

I am facing an issue extracting the month and year from the data (in Character varying type) >> InvoiceDate in SQL Postgres. I have seen the solution is relatively easy with MySQL function: DATEFROMPARTS as per the below Code which is not available in SQLpostgres. How can I get the same result DATA_PART function in Postgres SQL, but simultaneously I need to change the data type of the column "InvoiceDate" to the date
Select
CustomerID,
min(InvoiceDate) first_purchase_date,
DATEFROMPARTS(year(min(InvoiceDate)), month(min(InvoiceDate)), 1) Cohort_Date
into #cohort
from #online_retail_main
group by CustomerID
The output:
Customer ID| first_purchase_date |Cohort_Date|
-----------+-------------------------+-----------+
12345 | 2010-12-20 15:47:00:00 | 2010-12-01|
I am trying to make a date consits of Year and Month , while the day to be set as 1 for all

Assuming a valid Postgres timestamp:
select date_trunc('month', '2010-12-20 15:47:00.00'::timestamp)::date;
date_trunc
------------
12/01/2010
--or ISO format
set datestyle = 'ISO,MDY';
select date_trunc('month', '2010-12-20 15:47:00.00'::timestamp)::date;
date_trunc
------------
2010-12-01
Uses date_trunc to truncate the timestamp to a month which means the first of the month. Then cast(::date) to a date type. The DateStyle just deals with how the value is presented to the user. The value is not stored formatted.
To do something similar to what you did in MySQL:
select make_date(extract(year from '2010-12-20 15:47:00.00'::timestamp)::integer, extract(month from '2010-12-20 15:47:00.00'::timestamp)::integer, 1);
This uses make_date from here Date/time functions and extract to build a date.

Related

Converting varchar to date in postgresql (date_parse doesn't work)

Running this existing query in presto:
date(date_parse(activation_date, '%%m-%%d-%%Y')) from table1
gives the error
"Invalid format: "02/06/2022""
Activation_date is varchar, showing MM/DD/YYYY
How do I convert it to a date so that I can join it to a column that is already in postgresql date type? Thank you so much!
The expected format is %m/%d/%Y in Trino (formerly PrestoSQL).
trino> SELECT date(date_parse('02/06/2022', '%m/%d/%Y'));
_col0
------------
2022-02-06
https://trino.io/docs/current/functions/datetime.html?highlight=date_parse#mysql-date-functions
date_parse is not a Postgres function.
You don't need to escape % in Postgres strings.
Your format has - while your string has /.
If your DateStyle is set to MDY (Month Day Year), simply cast the string to a date.
# SELECT current_setting('datestyle');
current_setting
-----------------
ISO, MDY
# select '02/06/2022'::date;
date
------------
2022-02-06
See Date/Time Input for more.

Postgres query to get date and total amount grouped by day

I have a table Logs with fields
Amount,date
I need to get the sum of amount and months grouped by each day
I need to migrate my sqlite code to postgresql but i find the code migration kind of hard.The sqlite code is as follows
SELECT SUM(amount),transaction_date FROM log WHERE user_id = 1 AND strftime('%Y', transaction_date) = '2019' GROUP BY strftime('%d', transaction_date);
What i need to is date and total amount grouped by day for the year 2019
You need extract() function instead of strftime() to get the year and cast transaction_date to date only if it is timestamp, if it is of data type date remove the casting ::date:
SELECT
SUM(amount),
transaction_date::date
FROM log WHERE user_id = 1 AND extract(year from transaction_date) = 2019
GROUP BY transaction_date::date

Timestamp with timezone in PostgreSQL 9.6

I am currently searching my transaction table using the following query. The second TO_TIMESTAMP is specified as 2019-08-21..
SELECT t.* FROM Transaction t WHERE t.datetime >= TO_TIMESTAMP('2019-01-01T07:54:34','YYYY-MM-ddTHH:MI:SS')
AND t.datetime < TO_TIMESTAMP('2019-08-21T14:38:34','YYYY-MM-ddTHH:MI:SS') AND (t.location_1 = 2001 OR t.location_2 = 2001);
It returns me the following result:
When i change the second TO_TIMESTAMP to 2019-08-22.. It returns me the current day's result. I am not sure why I need to add one more day in order to retrieve the current day's result..
The current timezone in the PostgreSQL 9.6 is:
This is your problem:
SELECT TO_TIMESTAMP('2019-08-21T14:38:34','YYYY-MM-ddTHH:MI:SS');
to_timestamp
------------------------
2019-08-21 00:38:34+00
(1 row)
The unescaped T confuses the parser (the actual result may even be buggy).
Use the correct format string:
SELECT TO_TIMESTAMP('2019-08-21T14:38:34','YYYY-MM-DD"T"HH24:MI:SS');
to_timestamp
------------------------
2019-08-21 14:38:34+00
(1 row)

Date comparison in Netezza does not work properly

I am trying to run a simple query that excludes all records from the table which are greater than the maximum value of a date column. e.g.
SELECT * FROM TABLE1
WHERE LD_TMSTMP > (SELECT MAX(LD_TMSTMP) FROM TABLE1)
===========================================
0 records returned
This query should return zero records and it does that. However when I try to run the inner query I get this:
SELECT MAX(LD_TMSTMP) FROM TABLE1
===========================================
2015-04-22 06:42:32
And when I put this value in the same query I get 131 records
SELECT * FROM TABLE1
WHERE LD_TMSTMP > TO_DATE('2015-04-22 06:42:32','YYYY-MM-DD HH24:MI:SS')
===========================================
131 records returned
Does anyone know why this happens? Do I need to use a better precision value when returning the date in string format?
The problem here is that you are confusing DATE with TIMESTAMP. The tipoff is in your title, which references a DATE, but your data shows you are clearly dealing with a TIMESTAMP.
From your SQL we can see you are using TO_DATE rather than TO_TIMESTAMP to convert your character representation, which unsurprisingly gives us a DATE.
TESTDB.ADMIN(ADMIN)=> select TO_DATE('2015-04-22 06:42:32','YYYY-MM-DD HH24:MI:SS');
TO_DATE
------------
2015-04-22
(1 row)
TESTDB.ADMIN(ADMIN)=> select to_timestamp('2015-04-22 06:42:32','YYYY-MM-DD HH24:MI:SS');
TO_TIMESTAMP
---------------------
2015-04-22 06:42:32
(1 row)

ORA-01843: not a valid month - but what month format? Oracle 11g

I want to know what other MONTH formats exist except MM , MONTH or MON.
When the query below runs it gives me an error ORA-01843: not a valid month and I can understand why, because the server removes the "0" from the month "07" and leaves only the number "7", so the MM format is not the right one.
But which one is it?
select to_char(to_date(START_DATE,'MM/DD/YYYY '), 'DD-MM-YYYY')
from PER_ALL_PEOPLE_F
WHERE person_id=12345
The START_DATE column is DATE TYPE and it provides results like: 7/17/2012 .
Your assumption that the single-digit 7 for the month is a problem is not correct; Oracle is generally quite flexible and will happily parse a single digit month with the MM model:
select to_date('7/17/2012', 'MM/DD/YYYY') from dual;
TO_DATE('7/17/2012'
-------------------
2012-07-17 00:00:00
If start_date is already a DATE type then you should not be calling to_date() for it. You're doing an implicit conversion to a string using your NLS_DATE_FORMAT moodel, and then back to a date with your specified format. So really you're doing:
select to_char(to_date(to_char(START_DATE, <NLS_DATE_FORMAT>),
'MM/DD/YYYY '), 'DD-MM-YYYY')
If your NLS_DATE_FORMAT is something other than MM/DD/YYYY, e.g. DD-MON-YYYY, then you'll get an ORA-1843 error for at least some values.
You can see this with:
select to_date(date '2014-01-16', 'MM/DD/YYYY') from dual;
or the expanded:
select to_date(to_char(date '2014-01-16', 'DD-MON-YYYY'),
'MM/DD/YYYY') from dual;
Dates do not have any specific format, they're stored in an internal representation and then converted to a formatted string for display. You said your dates display like 7/12/2012, but given the error you're seeing your client seems to be doign that formatting, and it isn't related to the session NLS_DATE_FORMAT.
You only need to do:
select to_char(START_DATE, 'DD-MM-YYYY')