I have the following query. And I am calculating on MYDATE column which is a DECIMAL(8, 0) data type which stores datea in numeric form in YYYYMMDD format like this 20191107.
SELECT DECIMAL((TO_CHAR(TO_DATE(CAST(CAST(MYDATE AS INT) AS VARCHAR(8)), 'yyyymmdd') - 3 MONTHS, 'yyyymmdd')), 8, 0) FROM PDF_TABLE;
It works fine. However, when I use the above conversion in a WHERE clause like below, query does not return anything.
SELECT * FROM PDF_TABLE WHERE MYDATE = DECIMAL((TO_CHAR(TO_DATE(CAST(CAST(MYDATE AS INT) AS VARCHAR(8)), 'yyyymmdd') - 3 MONTHS, 'yyyymmdd')), 8, 0);
Example
Above is the data as is. Now I pass the date 20200601 as parameter in the WHERE clause of the following query, it should return the following row after subtracting 3 months from 20200601.
SELECT * FROM PDF_TABLE WHERE MYDATE = DECIMAL((TO_CHAR(TO_DATE(CAST(CAST(MYDATE AS INT) AS VARCHAR(8)), 'yyyymmdd') - 3 MONTHS, 'yyyymmdd')), 8, 0);
Try this as is:
WITH MYTAB (PDF_VOLUME, MYDATE) AS
(
VALUES
('110 GB', DEC(20200101, 8))
, ('120 GB', DEC(20200301, 8))
, ('390 GB', DEC(20200601, 8))
)
SELECT *
FROM MYTAB
WHERE MYDATE = DEC(TO_CHAR(TO_DATE(CHAR(CAST(? AS DEC(8))), 'YYYYMMDD') - 3 MONTH, 'YYYYMMDD'), 8);
How could it possibly return anything?
WHERE MYDATE = DECIMAL((TO_CHAR(TO_DATE(CAST(CAST(MYDATE AS INT) AS VARCHAR(8)), 'yyyymmdd') - 3 MONTHS
Dropping the conversions, you're asking WHERE MYDATE = MYDATE - 3 months
That's never going to be equal... Perhaps you forgot to change the inner MYDATE to CURRENT_DATE or something? That would also require the conversion to change..
Personally, I use a user defined function for this type of conversion; either write it yourself or download Alan Campin's free iDate source
WHERE MYDATE = ConvertToIDate(CCURRENT_DATE - 3 months, '*CCYMD');
Related
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;
Receive date as "19-May" and need to convert it as '05/01/2019', "19-June" to '06/01/2019'.
I have tried various date conversion but it didn't work.
You can try this. Storing date in this format is not a good/suggestion you should use the proper data type which are meant and available for.
You should update the values with proper date time value and then change the data type also. It will save your time & you do not need these conversions every time.
Select Try_Cast('19-May 2019' as Datetime)
OR
Select Try_Cast('19-May' + '2019' as Datetime)
To get the first date of month you can try the below query.
SELECT DATEADD(month, DATEDIFF(month, 0, Try_Cast('19-May 2019' as Datetime)), 0) AS StartOfMonth
Edit
To get the first date of month as per the given data in string, you can use the below query.
declare #dateinStr varchar(20) = '19-May'
Select try_cast('01-' + Replace(#dateinStr, LEFT(#dateinStr, 3), '') + LEFT(#dateinStr, 2) as Datetime) as Date
Here is the demo.
I suppose the months will be 3 chars only, if so then
Select s,
try_Cast(concat(right(s, 3), ' 2019') as Datetime)
from
(
values
('19-May'),
('19-Jun')
) t(s);
If the months is really comes like "June" & "August" then
select s,
try_cast(concat(substring(s, charindex('-',s)+1, 3), ' 2019') as date)
from
(
values
('19-May'),
('19-June'),
('15-August')
) t(s);
If you need to format it as mm/dd/yyyy then use 101 style.
You can do :
SELECT DATEADD(DAY, 1, EOMONTH(CONVERT(DATE, Dates + '-2019'), -1))
FROM ( VALUES ('19-May'), ('19-June')
) t(Dates);
How can I subtract one month from mm/yy in SQL?
For an example from 02/23 to 01/23.
Since your date format is not the recommended one. But for your scenario, you can use the following query to get your expected result.
Using DATEFROMPARTS() and string functions you can construct as a date and the DATEADD(MONTH, -1, date) will help to subtract one month.
DECLARE #TestTable TABLE (DateVal VARCHAR(5));
INSERT INTO #TestTable (DateVal) VALUES ('02/23'), ('01/23'), ('03/30');
SELECT DateVal,
RIGHT(CONVERT(VARCHAR(8), DATEADD(MONTH, -1, DATEFROMPARTS(RIGHT(DateVal, 2), LEFT(DateVal, 2), '01')), 3), 5) AS Result
FROM #TestTable
Result:
DateVal Result
----------------------
02/23 01/23
01/23 12/22
03/30 02/30
Demo on db<>fiddle
I think you need to use convert() to get a valid date, then dateadd() to subtract 1 month and finally format() to get the date in the string format:
select
format(dateadd(month, -1, convert(date, concat('01/', datecolumnname), 3)), 'MM/yy')
from tablename
See the demo.
This comes with a warning is super ugly but if you want string previous month then string again, maybe convert to date do the dateadd then back to string, horrid!
with cte_d
as
(select '01/23' as stringdate
union
select '12/17' as stringdate
)
select stringdate
,cast(Month(dateadd(month,-1,cast(right(stringdate,2)
+ left(stringdate,2) + '01' as date))) as nvarchar(2))
+'/'+
right(cast(Year(dateadd(month,-1,cast(right(stringdate,2)
+ left(stringdate,2) + '01' as date))) as nvarchar(4)),2) as [NewDate]
from cte_d
I have a table that has columns reportyear and reportmonth. For reportyear, the column is a vharchar (4) that equals to year 2016 format. For reportmonth, it is a varchar (2) that has a 01, 02, 03, etc. format. I have a data parameter that concatenates the two since our end users want a drop down date. So my parameter is #ReportDate varchar (7).
My problem is for one of my selects in my stored procedure, I need to put a where clause where it goes back a month. So if my parameter equals to '2016-11', I want a where clause where it returns '2016-10'. I have successfully done this using the flowing query:
SUBSTRING(#Reportdate, 1, 4) + '-' + cast(substring(#ReportDate, 6, 7) -1 as varchar(20))
This returns '2016-10' if I pick '2016-11' as any report date parameter.
But upon further thinking, this would not work if my report date is in January because the above query just literally subtract a string value. So if I pick '2016-01', the above query would return '2016-0'.
For Example:
Declare #Reportdate varchar(7) = '2016-01'
Select AsDate = dateadd(MM,-1,#ReportDate+'-01')
,AsSting = left(convert(date,dateadd(MM,-1,#ReportDate+'-01'),101),7)
Returns
AsDate AsSting
2015-12-01 2015-12
You can just use case:
select concat(#ReportYear - 1,
(case when #ReportMonth = '01' then '12'
else right(concat('0', #ReportMonth - 1))
end)
)
SQL Server will treat the strings as ints -- with no conversion errors for your values. concat() then converts them back into strings.
EDIT:
I see, this is backwards. Let's add one to the columns in the table and compare to #Report_Month:
where (reportmonth = 12 and
right(#ReportDate, 2) = '01' and left(#Report_date, 4) = reportyear + 1
) or
(left(#ReportDate, 4) = reportyear and
right(#ReportDate, 2) = reportmonth + 1
)
But after considering this, I think you should use a computed column:
alter table t add reportdate as ( datefromparts(reportyear, reportmonth, 1) );
Then simply do:
where dateadd(month, 1, reportdate) = cast(#reportdate + '01' as date)
Of course, you can do the explicit comparison:
where (dateadd(month, 1, datefromparts(reportyear, reportmonth, 1)) =
cast(#reportdate + '01' as date)
)
Note that both of these assume that #reportdate is a string.
I have this query
select CONVERT(varchar(5), tdate ,108) AS [Time] from table
which gives me the time in 24 hour format( military)
I wanted to convert it into a 12 hour format so i tried the query below
select SUBSTRING(CONVERT(VARCHAR, tdate, 100),13,2) + ':'
+ SUBSTRING(CONVERT(VARCHAR, tdate, 100),16,2) + ''
+ SUBSTRING(CONVERT(VARCHAR, tdate, 100),18,2) AS T
from table
and i get the 12 hour format but I am just curious if there is a shorter or better way of doing it. any help?
If you want to convert the current datetime for example:
SELECT CONVERT(VARCHAR, getdate(), 100) AS DateTime_In_12h_Format
Instead of getdate() you can put your desired column in a query (such as tdate in your example). If you want JUST the time in 12h and not the date and time use substring/right to separate them. It seems that you already know how to =).
This page lists every datetime conversion. It's really handy if you need other types of conversions.
This will return just the time, not the date.
SELECT RIGHT(CONVERT(VARCHAR, getdate(), 100), 7) AS time
For your table data:
select RIGHT(CONVERT(varchar, tdate ,100), 7) AS [Time] from table
Below code will return only time like 10:30 PM
SELECT FORMAT(CAST(getdate() AS DATETIME),'hh:mm tt') AS [Time]
Get date of server
SELECT LTRIM(RIGHT(CONVERT(VARCHAR(20), GETDATE(), 100), 7))
or
If it is stored in the table
SELECT LTRIM(RIGHT(CONVERT(VARCHAR(20), datename, 100), 7))
Result:
11:41AM
ifnull(date_format(at.date_time,'%d/%m/%Y'),"") AS date_time,
ifnull(time_format(at.date_time ,'%h:%i:%s'),"") AS date_time
This is how a SQL procedure looks...(for separating date and time)..there is no need of a special column for time/date....
Note:if H instead of h it will show the "hour in 24 hour" format