I have this table:
Original_Date Date_ Date_1 YearMonth YearMonth_1
03-07-2020 2020-07-03 2020-06-03 03-0 2020
13-03-2020 2020-03-13 2020-02-13 13-0 2020
08-01-2020 2020-01-08 2019-12-08 08-0 2019
13-11-2020 2020-11-13 2020-10-13 13-1 2020
23-03-2020 2020-03-23 2020-02-23 23-0 2020
30-07-2020 2020-07-30 2020-06-30 30-0 2020
13-07-2020 2020-07-13 2020-06-13 13-0 2020
24-01-2020 2020-01-24 2019-12-24 24-0 2019
05-10-2020 2020-10-05 2020-09-05 05-1 2020
11-07-2020 2020-07-11 2020-06-11 11-0 2020
Where if I use TYPE()
function on them they return:
Original Date: VARCHAR
Date_: DATE
Date_1: DATE
YearMonth_1: VARCHAR
YearMonth: VARCHAR
These columns are built based on Original_Date
column, where:
SELECT
Original_Date
CAST(Original_Date AS DATE FORMAT 'DD-MM-YYYY') AS Date_, -- This is in a subquery, put for simplicity I put it here
ADD_MONTHS(CAST(Original_Date AS DATE FORMAT 'DD-MM-YYYY'),-1) AS Date_1, -- This is in a subquery, put for simplicity I put it here
LEFT(CAST(Date_ AS varchar(10)),4) AS YearMonth,
LEFT(CAST(Date_1 AS varchar(10)),4) AS YearMonth_1,
FROM TABLE
The problem is:
- I can't understand why
YearMonth
takes the last (right) four characters instead of the first (left) four characters. - I was looking for a
YearMonth
with typeDATE
and format likeYYYY-MM
. But as I didn't find any solution with Teradata (if you can provide one, it will be better than the workaround I'm doing now), I'm going forYYYYMM as integer
, but as you can see when I'm applyingLEFT()
function it seem to work like aRIGHT()
function, even when both (Date_
andDate_1
) have the same data types. why? How can I solve this?
EDIT
SELECT
LEFT(CAST(Date_ AS varchar(10)),4) AS YearMonth_v2,
LEFT(CAST(Date_1 AS varchar(10)),4) AS YearMonth_1_v2,
FROM TABLE
Results in:
YearMonth_v2 YearMonth_1_v2
03-07-2020 2020-06-03
13-03-2020 2020-02-13
08-01-2020 2019-12-08
13-11-2020 2020-10-13
23-03-2020 2020-02-23
30-07-2020 2020-06-30
13-07-2020 2020-06-13
24-01-2020 2019-12-24
05-10-2020 2020-09-05
11-07-2020 2020-06-11
Why transforming the data type of these columns behave differently even when both of them (Date
and Date_1
) have the same data type and date format?
SELECT CAST(Date_ AS varchar(10))
will probably help you to visualize whats happening.dd-MM-yyyy
it worth to assume thatcast
returns the date in the same format and you substring from this string. How the DBMS can know you need a year with substring after you turn it intoVARCHAR
?LEFT(..., 4)
?