Convert whole number to Month-Year - sql

I am working in SQL Server, I have a column of numbers that represent the year and the month, such as:
YearandMonth
------------
202108
202109
202110
How do I convert this to an output like this?
YearandMonth
------------
Aug-2021
Sept-2021
Oct-2021
Thank you in advance

Steps:
Get the year and the month from the number.
Create a date from the year and the month.
Get the abbreviated month name from that date.
Concatenate month name and year.
The query:
select
format(datefromparts(yearanddate / 100, yearanddate % 100, 1), 'MMM', 'en-US') +
'-' +
cast(yearanddate / 100 as varchar(4))
from mytable;

select DATE_FORMAT(CONCAT(`yearandmonth`,'01'), '%b-%Y') as 'YearandMonth' from test_table;
by adding the 1st day of each month it provides the standard format so we can just use DATE_FORMAT() to get the result we need.

For SQL Server 2008 this should work fine. Untested, of course:
with myTable as (
select * from (values(202108),(202109),(202110))v(YearAndMonth)
)
select Left(DateName(month,Convert(date,Cast(YearAndMonth *100+1 as varchar(8)))),3) + '-' + Left(Cast(YearAndMonth as varchar(6)),4)
from myTable

Related

Presto SQL date_format extract week of year

Documentation : https://prestodb.io/docs/current/functions/datetime.html
I have epoch timestamps from which I want to extract week of the year like 2021-32, 2020-50, 2021-02 and so on.
SELECT concat(date_format(from_unixtime((CAST(my_timestamp AS BIGINT) + 19800000)/1000), '%Y'),
'-' ,
date_format(from_unixtime((CAST(my_timestamp AS BIGINT) + 19800000)/1000), '%v'))
AS week
However I am getting up some wrong values like :
week = 2021-53 for Epoch-Time corresponding to Jan 1, 2021 or Jan 2, 2021. I understand that there is a sync issue happening here but that is definitely not something I want - How do I offset so that first day of week 1 starts from the beginning of the year.
In that case you should just get the count of days and calculate the week.
Something like this:
SELECT concat(date_format(from_unixtime((CAST(my_timestamp AS BIGINT) + 19800000)/1000), '%Y'),
'-' ,
ceiling(date_format(from_unixtime((CAST(my_timestamp AS BIGINT) + 19800000)/1000), '%j')/7))
AS week
I was able to solve it using week_of_year and year_of_week methods.
Docs : https://prestodb.io/docs/current/functions/datetime.html#week
Query :
SELECT concat(CAST(year_of_week(from_unixtime((CAST(my_timestamp AS BIGINT) + 19800000)/1000)) AS varchar(15)),
'-',
CAST(week_of_year(from_unixtime((CAST(my_timestamp AS BIGINT) + 19800000)/1000)) AS varchar(15))) as week
Had to introduce some extra casts to varchar since concat doesn't support multiple datatypes.
Edit :
Another issue with above solution is that week_of_year returns single-digit weeks like 1, 2 instead of 01, 02 - thus causing an issue while sorting with these week numbers.
I ended up using a combination of year_of_week to get the correct year, and the general date_format(date, '%v') for week-numbers.
Updated Query :
SELECT concat(CAST(year_of_week(from_unixtime((CAST(my_timestamp AS BIGINT) + 19800000)/1000)) AS varchar(15)),
'-',
date_format(from_unixtime((CAST(my_timestamp AS BIGINT) + 19800000)/1000), '%v'))
There is no sync issue here - it expected behaviour for date_format and it's MySQL counterpart.
Note, that you can use full format string on the date:
select date_format(timestamp '2021-01-01', '%Y-%v')
_col0
2021-53
You can try calculating week number by dividing day_of_year by 7:
select ceiling(day_of_year(timestamp '2021-01-01') / 7.0)
Related:
presto github issue
joda weekOfWeekyear docs

Get only month and year in SQL Server

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

How to convert an YYYY-MM-DD date to YYYY-MM date

In SQL. How to convert a column A from (YYYY-MM-DD) to (YYYYMM)? I want to show the dates in YYYYMM format instead of YYYY-MM-DD.
Data type is TIMESTAMP. Using Teradata Studio 15.10.10.
For Teradata either use
to_char(tscol, 'YYYYMM') -- varchar result
or
extract(year from tscol) * 100 + extract(month from tscol) -- integer result
In Teradata you can format dates pretty much at will. To get YYYYMM, you would use
select <your date> (format 'yyyymm') (char(6))
Your date column needs to be actual date for this, not a string.
There are 3 functions you'll need.
MONTH() function. Returns the MONTH for the date within a range of 1 to 12 ( January to December). It Returns 0 when MONTH part for the date is 0.
YEAR() function. Returns a 4 digit YEAR.
CONCAT() function is used to concatenate two or more strings together.
So here's an example of combining the 3 functions.
SELECT CONCAT(YEAR('1969-02-18'),MONTH('1969-02-18'))
or you can do it in one with
select DATE_FORMAT('1969-02-18','%Y%m')
So to answer your question if it is referring to column A, you can use
SELECT DATE_FORMAT(A,'%Y%m')
SQL Fiddle:
http://www.sqlfiddle.com/#!9/a6c585/48362
You can use DATEPART to get the year and month parts of the date, cast to a varchar, pad and the concaternate.
SELECT DATEPART(YEAR,GETDATE())
SELECT DATEPART(MONTH,GETDATE())
SELECT CAST(DATEPART(YEAR,GETDATE()) AS VARCHAR(4)) + RIGHT('00' + CAST(DATEPART(MONTH,GETDATE()) AS VARCHAR(2)),2)

Hardcode a specific day in data time while pulling the data - SQL

Actually I have different date in SQL table when I pull those via SQL query, day of datetime field should have fixed day.
Example: (DD-MM-YYYY) day should be "7" > (7-MM-YYYY)
10-08-2007 > 07-08-2007
27-12-2013 > 07-12-2013
01-03-2017 > 07-03-2017
Can someone help me on this. Thanks in Advance.
Find the difference between 7 and the day of the original date and add that to the original date:
SELECT DATEADD(DAY, 7 - DAY(OriginalDate), OriginalDate)
Use DATEPART to take out the month and year parts. Cast those into varchar and concatenate with 07.
Query
select '07-' +
cast(DATEPART(mm, [date_column]) as varchar(2)) + '-' +
cast(DATEPART(yyyy, [date_column]) as varchar(4))
from your_table_name;
Assuming You might have to change the day number example
DECLARE #dayNum char(2)
SELECT #dayNum = '07'
select #dayNum + Right(convert(char(10),getdate(),105),8)
If that is not the case You could do this
select '07'+ Right(convert(char(10),'10-08-2007',105),8)
I'd go this way:
SELECT CONVERT(DATE,CONVERT(VARCHAR(6),GETDATE(),112)+'25',112);
CONVERT with format 112 will return the date as unseparated ISO (today we would get 20170407). Convert this to VARCHAR(6) will implicitly cut away the day's part (201704).
Now we add a day and use again CONVERT with 112, but now with DATE as target type.
One thing to keep in mind: The day you add must be two-digit. You can achieve this with
DECLARE #int INT=7;
SELECT REPLACE(STR(#int,2),' ','0');
Use DATEFROMPARTS: Updated ONLY works from 2012 - OP has tagged SQL-Server 2008
select DATEFROMPARTS ( year('10-08-2007'), month('10-08-2007'), 7 )
Assuming that your field is of datetime datatype and your fixed day is of integer type.
select datetimecolumn+(yourparamfixedday-datepart(dd,datetimecolumn))

Count with last 4 digits which represent Date

I have a question
Can we convert date 20-06-2011 (dd-mm-yyyy) into 0611 using sql (SQL server database) ?
And
Can we count ID below
keeping in mind last 4 digits which represent date (last 4 digits represent date in the form MMYY) so numbers with last 4 digits 0611 count should be 3
What would be the SQl Query for the count?
ID
AOB2340511
AOB4560511
AOB3500611
AOB4410611
AOB5120611
AOB1250411
EDIT: Corrected DATE data type option.
If your date fields are DATE data types you can do the following.
SELECT RIGHT('0' + CAST(DATEPART(MM, #TheDate) as VARCHAR), 2)
+ RIGHT(CAST(DATEPART(YY, #TheDate) as VARCHAR), 2)
If your date fields are stored as a string type, such as VARCHAR, NVARCHAR, etc, then try the following
select SUBSTRING(TheDate, 4, 2) + SUBSTRING(TheDate, 9, 2)
For the question about count, you can try this
SELECT RIGHT(ID, 4) AS TheDate, Count(*) AS TheCount
FROM MyTable
GROUP BY RIGHT(ID, 4)
If you need a query for the count that also shows the ID value, give this a try
SELECT ID, RIGHT(ID, 4) as MMYY,
COUNT(*) OVER (PARTITION BY RIGHT(ID, 4)) AS TheGroupCount
FROM MyTable
ORDER BY ID
This gives you "YYMM":
SELECT SUBSTRING(CONVERT(VARCHAR,getdate(),12),1,4)
To get the 2-digit month before the 2-digit year you need to do:
SELECT SUBSTRING(CONVERT(VARCHAR,getdate(),12),3,2) + SUBSTRING(CONVERT(VARCHAR,getdate(),12),1,2)
getdate() is just the current datestamp; substitute that with the date field you want to reformat.
CONVERT(...,12) gives you YYMMDD datestamp. See this helpful page for more magic numbers to use as the 3rd parameter: http://sql.dzone.com/news/custom-date-formatting-sql-ser
(BTW, using DATEPART(MM,getdate()) gives a 1-digit month not 2 digits, and DATEPART(YY,getdate()) gives a 4-digit year, not 2 digits. I.e. the DATEPART approach seems doomed)