Trying to create a new column "FiscalQrtr" that uses "Date" column in a case when, but am unable to figure it out so I went the update approach and am receiving an error message that states
"Conversion failed when converting the varchar value '%02' to data
type int".
The date column I believe is YYYYMM, so an example result would be: if Date = 200103 then FiscalQrtr = 200101
Update code looks like this:
select *
into #claims1
FROM #claims
update #claims1
set Date = left(Date, len(Date)-2) + '01'
where Date in ('%01','%02','%03');
Any help would be greatly appreicated
Why not just do all 4 quarters at once?
UPDATE #claims1
SET Date = LEFT(Date, 4) + '0' + RTRIM((RIGHT(Date,2)-1)/3+1);
If you don't like the unintuitive -1/3+1 math, you can write something that is much clearer in intent:
UPDATE #claims1 SET Date = LEFT(Date, 4) + '0' +
RTRIM(DATEPART(QUARTER, DATEFROMPARTS(LEFT(Date,4), RIGHT(Date,2), 1)));
If you just want to handle Q1 for some reason, ok, just add:
WHERE RIGHT(RTRIM(Date),1) < 4;
Example db<>fiddle
If the Date column is actually a 6 digit integer, representing YYYYMM, you can use a bit of arithmetic for this:
update #claims1
set Date = (Date / 100 * 100) + 1
where Date % 100 <= 3;
(Date / 100 * 100) truncates it, then you just add 1
You can also do all four quarters at once
update #claims1
set Date = (Date / 100 * 100) + (Date % 100 / 4 * 3 + 1);
This is because the data type of your column Date is INT and an INT data type cannot be used with LIKE. So instead, convert the Column to VARCHAR and perform the update. Like this
update #claims1
set Date = left(CAST(Date AS VARCHAR(20)), len(CAST(Date AS VARCHAR(20))-2)) + '01'
where RIGHT(CAST(Date AS VARCHAR(20)),2) in ('01','02','03');
Related
I want to fetch only month and year from a date column in SQL Server.
Example: if today's date is 02/03/2019, then I want 0319.
Note: I want the result in same order (2 digit month and 2 digit year). Zero should not be removed from month.
As an alternative approach, you could go for:
RIGHT(REPLACE(CONVERT(varchar(8),DateColumn,3),'/',''),4)
You can create a number using:
select month(datecol) * 100 + (year(datecol) % 100)
Prepending the zeros requires a bit more work:
select right('0' + convert(varchar(255), month(datecol) * 100 + (year(datecol) % 100)), 4)
Or, you can use format():
select format(datecol, 'MMyy')
You can try this
substring(convert(nvarchar,#date,12),3,2) + left(convert(nvarchar,#date,12),2)
You can create an user defined function, and then apply to your column/s
create function udf_Getmonthyear(#date as date)
RETURNS nchar(4)
BEGIN
DECLARE #d_format nchar(6) = (select convert(nvarchar,#date,12))
RETURN (select SUBSTRING(#d_format,3,2) + left(#d_format,2))
end
go
Use function DATEPART in TSQL to get any part of a DateTime value. e.g:
DATEPART(yy,datecol) gives you 4 digit year part of a DateTime column (e.g: datecol), using the % (modulus) operator you can get 2 digit year DATEPART(yy,datecol)%100.
DATEPART(mm,datecol) gives you month part of the datecol field.
select Right('0'+cast(DATEPART(mm,datecol) as varchar(2)),2) +
Right('0'+cast(DATEPART(yy,datecol)%100 as varchar(2)),2) MonthYearPart
from MyTable
Regards
My query get the time for a column called "OBRGTM" is '112532'. I need to convert this format to '11:25:32' I mean from hhmmss to hh:mm:ss
If your SQL-server version support FORMAT method you can use this.
TEST DDL
CREATE TABLE T(
dt numeric
);
INSERT INTO T VALUES (112532);
INSERT INTO T VALUES (012532);
INSERT INTO T VALUES (012530);
Query
SELECT FORMAT(dt,'0#:##:##')
FROM T
[Results]:
| |
|----------|
| 11:25:32 |
| 01:25:32 |
| 01:25:30 |
SQLFIDDLE
Try below code:
Use LEFT function to remove or eliminate the leading 0000000 after last decimal point
SELECT LEFT(CONVERT(TIME,STUFF(STUFF(RIGHT(OBRGTM,6),5,0,':'),3,0,':')),8) as OBRGTM
To test:
DECLARE #TimeString NUMERIC
SET #TimeString = 232320
SELECT LEFT(CONVERT(TIME,STUFF(STUFF(RIGHT(#TimeString,6),5,0,':'),3,0,':')),8)
If the value is a string, you can produce a string of the right format using stuff():
select stuff(stuff(OBRGTM, 5, 0, ':'), 3, 0, ':')
You can convert this to a time using cast() or convert():
select convert(time, stuff(stuff(OBRGTM, 5, 0, ':'), 3, 0, ':'))
If it was an integer, you could use integer division to calculate the number of seconds since midnight and make it a datetime that can easlily be formatted:
DECLARE #OBRGTM int = 123456;
SELECT DATEADD(second, #OBRGTM - 40*(#OBRGTM/100 + 60*(#OBRGTM/10000)), 0);
Added:
For those who are interested in the mathemagic behind this:
If x is the integer consisting of the digits hhmmss, then let's use integer division and define x' := x/100 and x" := x/10000. This way, x' will be the integer hhmm and x" will be just the hours (hh).
Now, we can retrieve the seconds (ss), minutes (mm) and hours (hh) of the time hh:mm:ss using:
ss = x - 100*x'
mm = x' - 100*x"
hh = x"
Putting it all together, the total number of seconds after midnight is
ss + 60*mm + 3600*hh
= x - 100*x' + 60*(x' - 100*x") + 3600*x"
= x - 100*x' + 60*x' - 6000*x" + 3600*x"
= x - 40*x' - 2400*x"
= x - 40*(x' + 60*x")
My task is to compare dates in two different tables in a Teradata database. In table group_1 dates are BIGINT, for instance 20,141,106 and in table group_2 dates are VARCHAR(30), for instance, 11/12/2015.
What would be the best way to do a conversion and compare them, namely,
select * from ....
where date in group_1 = date in group_2?
Many thanks in advance.
Can you safely convert those columns to dates (no invalid dates)?
BIGINT -> DATE:
cast(col - 19000000 as date)
VARCHAR -> DATE:
to_date(col, 'dd/mm/yyyy') (or 'mm/dd/yyyy'?)
Otherwise:
BIGINT -> VARCHAR:
TRIM((col MOD 100) * 1000000 + (col/100 MOD 100) * 10000 + (col / 10000) (FORMAT '99/99/9999')) -- dmy
or
TRIM((col/100 MOD 100) * 1000000 + (col MOD 100) * 10000 + (col / 10000) (FORMAT '99/99/9999')) -- mdy
And next time, try to store data using the correct datatype or at least the same wrong type :-)
You should convert date types to date for comparisons and other operations.
For the integer:
select to_date(convert(bigintcol as varchar(255)), 'YYYYMMDD')
For the string:
select to_date(varcharcol, 'MM/DD/YYYY') -- or perhaps DD/MM/YYYY
You can then compare the dates directly.
I am trying to find a data with specific where clause of date and month but I am receiving an error can anyone help me with this?
select *
from my_data
where date BETWEEN '11-20' AND '12-15'
MS SQL Server Management Studio
I am receving an error
Conversion failed when converting date and/or time from character string
Most databases support functions to extract components of dates. So, one way of doing what you want is to convert the values to numbers and make a comparison like this:
where month(date) * 100 + day(date) between 1120 and 1215
The functions for extracting date parts differ by database, so your database might have somewhat different methods for doing this.
The conversion is failing because you are not specifying a year. If you were to specify '11-20-2015' your query would work just insert whatever year you need.
SELECT *
FROM my_data
WHERE date BETWEEN '11-20-2015' AND '12-15-2015'
Alternatively if you wanted data from that range of dates for multiple years I would use a while loop to insert information in a # table then read from that table, depending on the amount of data this could be quick or sloooowww here is an example.
DECLARE #mindatestart date, #mindateend date, #maxdatestart date
SET #mindatestart = '11-20-2010'
SET #mindateend = '12-15-2010'
SET #maxdatestart = '11-20-2015'
SELECT top 0 *, year = ' '
INTO #mydata
FROM my_data
WHILE #mindatestart < #maxdatestart
BEGIN
INSERT INTO #mydata
SELECT *, YEAR(#mindatestart)
FROM my_data
where date between #mindatestart and #mindateend
SET #mindatestart = DATEADD(Year, 1, #mindatestart)
SET #mindateend = DATEADD(Year, 1, #mindateend)
END
This will loop and insert the data from 2010-2015 for those date ranges and add a extra column on the end so you can call the data and order by year if you want like this
SELECT * FROM #mydata order by YEAR
Hopefully some part of this helps!
FROM THE COMMENT BELOW
SELECT *
FROM my_data
WHERE DAY(RIGHT(date, 5)) between DAY(11-20) and DAY(12-15)
The reason '11-20' doesn't work is because its a character string which is why you have to input it between ' ' What the Month() function does is take whatever you put between the () and convert it to an integer. Which is why you're not getting anything back using the method in the first answer, the '-Year' from the table date field is being added into the numeric value where your value is just being converted from 11-20 you can see by using these queries
SELECT MONTH(11-20) --Returns 12
SELECT MONTH(11-20-2015) -- Returns 6
SELECT MONTH(11-20-2014) -- Returns 6
Using RIGHT(Date, 5) you only get Month-day, then you date the day value of that so DAY(RIGHT(DATE, 5) and you should get something that in theory should fall within those date ranges despite the year. However I'm not sure how accurate the data will be, and its a lot of work just to not add an additional 8 characters in your original query.
Since you only care about month and day, but not year, you need to use DATEPART to split up the date. Try this:
select *
from my_data
WHERE 1=1
AND (DATEPART(m, date) >= 11 AND DATEPART(d,date) >= 20)
AND (DATEPART(m, date) <= 12 AND DATEPART(d,date) <= 15)
I'm trying to query a table that has a varchar(100) "VALUE" column. This column can hold anything from a letter, a number or, in this case, a date.
The date will always be entered in the table as 'YYYY-mm-dd'. However, when I run the following query:
select * from myTable
where VALUE = '2009-12-11' (Date, Format 'yyyy-mm-dd')
I receive the following error:
Invalid date supplied for myTable.VALUE.
Example of the value table:
(1,'122')
(2,'red')
(3,'2009-12-11')
Any ideas as to what might be causing this?
Thanks!
if the data type is declared as varchar, it should just treat it like a string.
try not specifying anything about the date format, like
select * from myTable
where VALUE = '2009-12-11'
If you run an explain on the query, you can see that it's casting value to date before comparing against your supplied value. If you have another column that accurately records the type of what's in VALUE, you can add that to the where clause and you will no longer get the error (see below). Otherwise, go with Beth's recommendation.
select * from myTable
where VALUE = '2009-12-11' (Date, Format 'yyyy-mm-dd')
and VALUE_TYPE = 'DATE';
Teradata internal date calculation is (year - 1900) * 10000 + (month * 100) + day.
So if date is 02/11/2009 (2nd November 2010) then
=(2009-1900) * 10000 + (11 * 100) + 2
=109 * 10000 + 1100 + 2
=1090000 + 1100 + 2
=1090000
1100
2
----------
1091102
----------
So 2nd november 2009 is stored in Teradata as 1091102.
You can extract it in required format by casting (as u have it in varchar). Hope this helps.
Is it possible that VALUE is a reserved word in Teradata?
If so, you need to put that into double quotes:
select *
from myTable
where "VALUE" = '2009-12-11'