Combine columns, remove hyphen comma and space in Postgresql [duplicate] - postgresql

This question already has an answer here:
Alter the timestamp format in Postgres
(1 answer)
Closed 1 year ago.
I need to combine values from two columns into one and then remove the colons, spaces and hyphens.
SELECT
documentation.nsma1_date + documentation.nsma1_time AS "Start Date"
FROM
documentation
This returns column Start Date with data 2021-01-20 09:09:00
I have tried to get it to return 20210120090900 without any luck. Any idea how to do this? I have tried the REGEXP_REPLACE and FORMAT but to no avail.

Use to_char() from here Data formatting
--Assuming 2021-01-20 09:09:00 is timestamp
select to_char('2021-01-20 09:09:00'::timestamp, 'YYYYMMDDHHMISS');
to_char
----------------
20210120090900
UPDATE
select
to_char(documentation.nsma1_date + documentation.nsma1_time,'YYYYMMDDHHMISS') AS "Start Date";

Related

Can someone help me convert this sqlite query to a postgres query?

SELECT substr(strftime('%Y', date),3,2) AS month, 0 AS zero FROM listvalue
I have this query in SQLite, when I import it into Postgres I'm having problem translating the substr(strftime('%Y', date),3,2) part.
substr(strftime('%Y', date),3,2) extracts the last 2 digits of the year part of the column date, but in your code you alias it as month!
if you want to do the same in Postgresql you can use extract() to get the year, typecast it to varchar and use substr() to get the last 2 chars:
substr(extract(year from date)::varchar, 3, 2)
You can translate the expression with TO_CHAR function to PostgreSQL:
SUBSTR(TO_CHAR(date, 'YYYY'), 3, 2)
Note: The format %Y will return the year of the date and not the month as your query suggests.
The SQLite query will return the last to digits of year of the date. You can omit the SUBSTR in PostgreSQL call by using the apropriate format:
TO_CHAR(date, 'YY')
We suspect that you want to extract the last two digits of the year value from the date column. The strftime() function won’t work in Postgres server. So, suggest you to use either one of the below queries to achieve your requirement,
SELECT substring(date_part('year', date)::varchar, 3, 2) AS year, 0 AS zero FROM listvalue;
SELCT to_char(shipped_date, 'YY'), 0 AS zero from listvalue;
Thanks,
Renuka N.

how to format date column in kdb

I am newbie to KDB. I have a KDB table which I am querying as:
select[100] from table_name
now this table has got some date columns which have dates stored in this format
yyyy.mm.dd
I wish to query that table and retrieve the date fields in specific format (like mm/dd/yyyy). If this would've been any other RDBMS table this is what i would have done:
select to_date(date_field,'mm/dd/yyyy') from table_name
I need kdb equivalent of above. I've tried my best to go through the kdb docs but unable to find any function / example / syntax to do that.
Thanks in advance!
As Anton said KDB doesn't have an inbuilt way to specify the date format. However you can extract the components of the date individually and rearrange as you wish.
For the example table t with date column:
q)t
date
----------
2008.02.04
2015.01.02
q)update o:{"0"^"/"sv'flip -2 -2 4$'string`mm`dd`year$\:x}date from t
date o
-----------------------
2008.02.04 "02/04/2008"
2015.01.02 "01/02/2015"
From right to left inside the function: we extract the month,day and year components with `mm`dd`year$:x before stringing the result. We then pad the month and day components with a null character (-2 -2 4$') before each and add the "/" formatting ("/"sv'flip). Finally the leading nulls are filled with "0" ("0"^).
Check out this GitHub library for datetime formatting. It supports the excel way of formatting date and time. Though it might not be the right fit for formatting a very large number of objects (but if distinct dates are very less then a keyed table and lj can be used for lookup).
q).dtf.format["mm/dd/yyyy"; 2016.09.23]
"09/23/2016"
q).dtf.format["dd mmmm yyyy"; 2016.09.03] // another example
"03 September 2016"
I don't think KDB has built-in date formatting features.
The most reliable way is to format date by yourself.
For example
t: ([]date: 10?.z.d);
update dateFormatted: {x: "." vs x; x[1],"/",x[2],"/",x[0]} each string date from t
gives
date dateFormatted
------------------------
2012.07.21 "07/21/2012"
2001.05.11 "05/11/2001"
2008.04.25 "04/25/2008"
....
Or, more efficient way to do the same formatting is
update dateFormatted: "/"sv/:("."vs/:string date)[;1 2 0] from t
now qdate is available for datetime parsing and conversion

Convert 2-digit date to year in the 1900s

I am using the string manipulations functions in PostgreSQL 9.6 to convert a 2-digit text year into a 4 digit year. I am able to convert the string into a date and year, but the I keep getting years in the 2000s instead of the 1900s.
select extract(year from to_date('58', 'YY'));
This returns 2058 instead of 1958.
Now all of my 2 digit dates are in the 1900s, but I cannot find a max function or parameter in the to_date() function that forces the date into the 1900s.
Anyone know how to change this behavior?
Exact behavior is defined in the manual here:
If the year format specification is less than four digits, e.g. YYY, and the supplied year is less than four digits, the year will be adjusted to be nearest to the year 2020, e.g. 95 becomes 1995.
Bold emphasis mine.
Since 2058 is closer to 2020 than 1958, the first one is the result you get from to_date('58', 'YY').
There is currently no setting to override this behavior. You have to provide the desired century explicitly if you disagree with the default. Similar to what Haleemur commented:
SELECT to_date('19' || <2-digit-year-variable>, 'YYYY');
But to_date() takes text input, not integer. Integer input would raise an exception like:
ERROR: function to_date(integer, unknown) does not exist
And if by:
convert a 2-digit text year into a 4 digit year
... you mean a 4 digit text year, it's cleaner to use to_char():
SELECT to_char(to_date('19' || '58', 'YYYY'), 'YYYY')
to_char() can return text in variable formats (unlike extract(), which returns a double precision number).
If the input is valid 2-digit strings (nothing but exactly 2 digits), a simple concatenation does the job, too
SELECT '19' || <2-digit-year-variable>
to convert a 2 digit year stored as text to a 4 digit year like 19xx you can do something like this:
SELECT ('19' || '58')::int
or user klin suggested
select 1900+ '58'

Converting string to timestamp in DB2 with to many fractions of a second

I am trying to convert a string on the on the following format to a timestamp in DB2: 2015-09-07T09:15:25.4788396+04:00
Problem is, DB2 only seems to handle 6 digit fractional seconds, not 7 as in my case. Any thoughts on a good workaround?
The format you have there matches the xs:dateTime pattern from XML. You can use this to your advantage and use implied XML parsing:
SELECT XMLCAST(XMLCAST('2015-09-07T09:15:25.4788396+04:00' AS XML) AS TIMESTAMP)
FROM SYSIBM.SYSDUMMY1
1
--------------------------
2015-09-07-05:15:25.478839
Note the timestamp returned is in UTC, add + CURRENT TIMEZONE to return it as a local timestamp. Tested on DB2 z/OS DSN10015.
You will need to parse the timezone from the string. Once you have that you can get the UTC time from subtracting from "current timezone" then add the parsed timezone to it as shown below. You will also need to use REPLACE to change T to a dash and colons to dots.
SELECT (TIMESTAMP('2015-09-07-09.15.25.4788396') - (current timezone)) + 4 hours FROM sysibm.sysdummy1;

PostgreSQL, count of rows between min and max dates [duplicate]

This question already has an answer here:
PostgreSQL, min, max and count of dates in range
(1 answer)
Closed 8 years ago.
I am getting min and max dates from text column with query which good people helped me to get there like this :
SELECT max(to_date(nullif(mydatetxt,''), 'DD.MM.YYYY')),
min(to_date(nullif(mydatetxt,''), 'DD.MM.YYYY'))
FROM table_name;
How can I get COUNT of all matched rows between and including min and max dates (written in text column)?
All you really need to do is:
SELECT count(*), max(to_date(nullif(mydatetxt,''), 'DD.MM.YYYY')), min(to_date(nullif(mydatetxt,''), 'DD.MM.YYYY'))
FROM table_name;
Or maybe I misunderstood. Really, you should, if at all possible, move the date field to a date type. If you have to handle garbage input, use a view and an update trigger to do that.