Date conversions in sqlite - sql

I have a sqlite DB and the column dateID is stored as an integer e.g. 20131101 being Nov 1, 2013. I need to calculate # of days from the start of a period - say beginning of a period into a dayNumber column.
Here is my sql:
update temptable set dayNumber = dateid - (select min(dateid) -1 from temptable)
It was doing fine until I cross months e.g. 20131101 - (say) 20131017 and I get 85 instead of the 15 I had hoped for - Can anyone help me with the date conversions so I can get 15?

If you had your dates stored in one of the supported date formats, you could use the built-in date functions to do calculations on these values.
To convert from yyyymmdd to yyyy-mm-dd, use an expression like this:
substr(dateid, 1, 4) || '-' || substr(dateid, 5, 2) || '-' || substr(dateid, 7, 2)
To convert a date into a number of days, use, for example, julianday:
UPDATE temptable
SET dayNumber = julianday(substr(dateid, 1, 4) || '-' ||
substr(dateid, 5, 2) || '-' ||
substr(dateid, 7, 2)) -
(SELECT julianday(MIN(substr(dateid, 1, 4) || '-' ||
substr(dateid, 5, 2) || '-' ||
substr(dateid, 7, 2))) - 1
FROM temptable)

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;

Convert single digit months to double digit

I have a date column which have dates in these formats dd/mm/yyyy, d/m/yyyy.
So basically if the month is January it will have it as 1 instead of 01.
But if the month is October it will have it as 10.
How can i convert that column to be in yyyy/mm/dd format?
For example convert 1/1/2021 to 2021/01/01.
You can do it with string functions and implicit conversions of strings to integers:
SELECT SUBSTR(datecol, -4) || '/' ||
SUBSTR('0' || (SUBSTR(datecol, INSTR(datecol, '/') + 1) + 0), -2) || '/' ||
SUBSTR('0' || (datecol + 0), -2) date
FROM tablename
Change datecol to the name of your column.
If you want to update the column it is better to use the format 'YYYY-MM-DD' which is the only valid text date format for SQLite:
UPDATE tablename
SET datecol = SUBSTR(datecol, -4) || '-' ||
SUBSTR('0' || (SUBSTR(datecol, INSTR(datecol, '/') + 1) + 0), -2) || '-' ||
SUBSTR('0' || (datecol + 0), -2)
See a simplified demo.

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.

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.

DB2 date conversion

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