DB2 date conversion - sql

I have 2 INTEGER columns like the following:
Month Year
----- -----
5 2011
Is there any way to convert that to a single column VARCHAR like this: May-2011

I don't know of an easy way to do this since you don't have a date object (ie its not like youre finding the month of a timestamp), you can use a case statement but it gets long.
SELECT CASE Month
WHEN '1' THEN 'January'
WHEN '2' THEN 'February'
WHEN '3' THEN 'March'
WHEN '4' THEN 'April'
...
END+'-'+Year
FROM TABLE

I think this will do it:
SELECT
MONTHNAME(
DATE(CAST(Year AS CHAR(4)) || '-' || TRIM(CAST(Month AS CHAR(2))) || '-1')
) || '-' || CAST(Year AS CHAR(4))
FROM TABLE

This should do the trick, assuming that the columns Month and Year are integers and Month has the domain 1-12:
select substring('---JanFebMarAprMayJunJulAugSepOctNovDec', 3*Month , 3 )
+ '-'
+ right(digits(Year),4)
from some_table
If Month is 0 you'll get '---' as the month; if it's less than 0 or greater than 12, you'll get some sort of blooey.

You could create a function to convert the month value, like this...
CREATE FUNCTION INT2MONTH (MONTH INTEGER)
RETURNS VARCHAR(100)
LANGUAGE SQL
CONTAINS SQL
NO EXTERNAL ACTION
DETERMINISTIC
RETURN MONTHNAME('2000-' || RIGHT('0' || STRIP(CHAR(MONTH)), 2) || '-01')
Then you can...
select int2month(month) || '-' || strip(char(year)) from test
1
--------------------------------------------------
May-2011
June-2011
December-2012
If you want a 3 char month then change last last on function to...
RETURN LEFT(MONTHNAME('2000-' || RIGHT('0' || STRIP(CHAR(MONTH)), 2) || '-01'), 3)

I realize this question is pretty old, but there's a way that is a lot simpler than any of the options listed here (in my opinion) -- a combination of some date math and the VARCHAR_FORMAR() function:
SELECT
VARCHAR_FORMAT(
DATE('0001-01-01') + (month_col - 1) MONTH + (year_col - 1) YEAR
,'Month-YYYY'
)
FROM your_table

Related

How do I get yyyy-mm format from 2 different columns in SQL?

I have 1 column that displays year number in the format 1999 and I have another column that displays month number as 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12.
How do I get the single months to display with a 0 in front? I need to combine these 2 columns to display in the form of yyyy/mm so it will be 1999/01 for January 1999.
I tried:
SELECT
YearNumber + '/' + FORMAT(MonthNumber, 'mm') AS PaymentMonth
But I get this error:
Conversion failed when converting the varchar value '/' to data type smallint
Please try:
SELECT
CAST(YearNumber AS varchar(4)) + '/' +
LEFT('0' + CAST(MonthNumber AS varchar(2)), 2) AS PaymentMonth;
Another option, using case when:
The table:
select * from mytable
# YearNumber MonthNumber
# 1999 2
# 2000 11
select YearNumber || '/' ||
(case when MonthNumber < 10 then '0' else '' end) ||
MonthNumber as YearMonth
from mytable
# YearMonth
# 1999/02
# 2000/11
Note: the above works in sqlite, which tends to be more permissive with column types. In SQL Server, if the columns are not strings already then you may need to cast(YearNumber as char(4)) or perhaps use the concat function:
select
concat(YearNumber, '/',
(case when MonthNumber < 10 then '0' else '' end),
MonthNumber) as YearMonth
from mytable
Other DBMSes have different dialects, they may differ slightly.
SQL Date Format with the FORMAT function
Use the FORMAT function to format the date and time data types from a date column (date, datetime, datetime2, smalldatetime, datetimeoffset, etc. data type) in a table or a variable such as GETDATE()
To get DD/MM/YYYY use SELECT FORMAT (getdate(), 'dd/MM/yyyy ') as date
To get MM-DD-YY use SELECT FORMAT (getdate(), 'MM-dd-yy') as date.
You can use the concat() function to join them. Depending on the database you can use || instead.
select concat(col1, '/', col2) from tbl;
This is also standard, but not enabled by default on MySQL, and possibly other databases.
select col1 || '/' || col2 from tbl;

SQL Query to Combine Dates

I have a data set that has dates like this:
MM DD YY
2 8 10
3 9 11
4 10 12
I'm trying to write a query that displays the dates in one single column as MM/DD/YY
Any help would be greatly appreciated thanks
If you dont mind the data format, you can concatenate them.
select MM || '/' || 'DD' || '/' || YY DATE_COL from T
you can also convert it to date
select to_Date(MM || '/' || 'DD' || '/' || YY, 'MM/DD/YY') DATE_COL from T
Teradata actually stores dates as integers, as explained in the documentation:
Teradata Database stores each DATE value as a four-byte integer using the following formula: (year - 1900) * 10000 + (month * 100) + day.
If you want to generate a result of date datatype from your numbers, you can just do:
cast((yy + 100) * 10000 + mm * 100 + dd as date)
On the other hand, if you just want a string in format mm/dd/yy, it is probably simpler to use string functions; we just need to pad the 1-digit values with 0:
lpad(mm, 2, '0') || '/' || lpad(dd, 2, '0') || '/' || lpad(yy, 2, '0')
You can do below, assuming your year is in the 21st century.
select to_Date(lpad(MM,2,'0')|| '/' ||lpad(DD,2,'0')|| '/20' ||lpad(YY,2,'0'),'MM/DD/YYYY') as Date_field
from my_Table;
Here is a demo in Oracle - https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=1ba6814d793f2b8b269611e348540f6c. This would work in Teradata as well.

How can I convert an integer like 3212007 to date 3-21-2007 uisng IBM DB2 SQL?

The dataset I inherited has a DATE column but the values in this column are integers of the form 3212007 which should be 03-21-2007. I can't get it back into date format.
I can convert the integer to a string using CAST(myinteger as varchar(8)) without difficulty. Then I can CAST that as date by CAST(CAST(myinteger as varchar(8)) as date) which gets me a date. The problem is that my integer is formatted as 'mmddyyyy' so for 3212007, I get 3212-01-07.
select TRANSACTION_DATE from MA_NORFOLK fetch first row only;
[returns: 3212007]
select CAST(TRANSACTION_DATE as VARCHAR) from MA_NORFOLK fetch first row only;
[returns: 3212007]
select CAST(CAST(TRANSACTION_DATE as varchar(8)) as date) from MA_NORFOLK fetch first row only;
[returns: 3212-01-07]
Other posts suggest using CONVERT command, but all I get are errors
"DATE" is not valid in the context where it is used..."
Could you please advise me?
Try this:
date(to_date(digits(dec(3212007, 8)), 'MMDDYYYY'))
If you may have one digit for month, there is an alternative:
select
date
(
case when substr(char_dt, 1, 2)='00'
then translate('EFGH-0D-0C', char_dt, 'ABCDEFGH')
else translate('EFGH-AB-CD', char_dt, 'ABCDEFGH')
end
) dt, char_dt
from
(
select digits(dec(i, 8)) char_dt
from table(values 3212007, 312007) t(i)
) t;
DT CHAR_DT
---------- --------
2007-03-21 03212007
2007-01-03 00312007
This works (at least in MS SQL Server):
SELECT CAST(CONCAT( RIGHT(3212007,4),'-',
(3212007 / 1000000), '-', ((3212007 % 1000000) / 10000)) AS date)
The trick is that you don't know if you will have a single digit, or two-digit month, so you have to start with getting just the right 4 characters as the year. Then by using combinations of modulo and integer divide, you can parse out the month and day.
Of course, you will want to substitute your actual date column for the sample data that I used above.
I think this may works well:
create table #temp(
date int
)
insert into #temp (date)
values(3212007),
(12032019)
select
case when len(cast(date as varchar)) = 7
then
'0' + left(cast(date as varchar), 1) + '-' + substring(cast(date as varchar), 2,2) + '-' + right(cast(date as varchar), 4)
else left(cast(date as varchar), 2) + '-' + substring(cast(date as varchar), 3,2) + '-' + right(cast(date as varchar), 4) end
from #temp

Combining date , month , year columns in SQL Server

DD(10)-MM(05)-YYYY(2013)
I have a table with DATE, MONTH, YEAR in separate columns. How I can combine them into a single column Created date?
Output must be: 10-05-2013 (DD-MM-YYYY format)
SELECT RIGHT('00' + DAY, 2) + '-' + RIGHT('00' + MONTH, 2) + '-' + YEAR AS Date
FROM YourTable
I guess you want have a date field instead of a string. So use TO_DATE() function. You can format date anyway you want later.
TO_DATE(YEAR + '/' + MONTH + '/' + DATE, 'yyyy/mm/dd')
You can do it easily:
SELECT to_char(TO_DATE('10 01 2014', 'DD MM YYYY'),'dd-mm-yyyy') AS MYDATE FROM DUAL
To concatenate columns you just need to use "+" in your select statement
SELECT DATE + '-'+ MONTH + '-'+ YEAR FROM table

convert integer to Days

I'm looking to convert an integer to Days using a db2 database. The integers are in this format 20130101 or YYYYMMDD. I believe you have to write a custom function after converting the integer to a char but I was unsure of how to do the second conversion to DAYS. I'm looking for a returned format January, 1, 2013 from 20130101.
WITH
/*****************************************************
*** Sample Data ***
*****************************************************/
sample_data
( START_DATE , END_DATE ) AS
(
VALUES
(20130101, 20131227 )
, (20130930, 20131230 )
, (20130411, 20130912 )
, (20130410, 20140101 )
)
,
t2(START_DATE, END_DATE) AS
( SELECT
CAST(SUBSTR(START_DATE, 1,4) CONCAT '-'
CONCAT SUBSTR(START_DATE, 5,2) CONCAT '-'
CONCAT SUBSTR(START_DATE, 7,2) AS CHAR(15)),
CAST(SUBSTR(END_DATE, 1,4) CONCAT '-'
CONCAT SUBSTR(END_DATE, 5,2) CONCAT '-'
CONCAT SUBSTR(END_DATE, 7,2) AS CHAR(15))
FROM SAMPLE_DATA
)
SELECT
START_DATE,
END_DATE
FROM t2
You can use this:
select monthname(to_date(20130101, 'YYYYMMDD')) || ', ' ||
day(to_date(20130101, 'YYYYMMDD')) || ', ' ||
year(to_date(20130101, 'YYYYMMDD')) from sysibm.sysdummy1
The result is:
January, 1, 2013
Replace the integer 20130101 by your field name.
If you will be using the conversion in several places, it's probably better to create a function to avoid repeating the field and conversions.
You could also cut a few corners using aritmetics to get year and day, such as this:
select monthname(to_date(20130101, 'YYYYMMDD')) || ', ' ||
mod(20130101, 100) || ', ' || to_char(20130101 / 10000) from sysibm.sysdummy1
The result is the same.
It's a lot of casting, but you can use the TIMESTAMP_FORMAT function:
date(timestamp_format(char(start_date),'YYYYMMDD'))
Keep in mind that this just gets you a value that is an actual DATE, not necessarily in the "pretty" format that you list above.