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

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)

Related

Get first day of first month of previous year in yyyy-mm-dd format

How do I get the first day of the first month of previous year in yyyy-mm-dd format? ie. 2019-01-01.
This is the code I have tried:
SELECT DATEADD(yy,-1,DATEADD(yy,DATEDIFF(yy,0,GETDATE()),0))
You can use DATEFROMPARTS() function in SQL Server for creating date from given year, month and date in integer as shown below. To get the previous year you can use Year() function and subtract 1 from that. First date and month is always 1 so it has been hard-coded here.
declare #IntYear int = Year(Getdate()) - 1 --Previous Year
Select datefromparts(#Intyear, 1, 1)
The output in SSMS is as shown below.
To get the output in the different format you can follow this link.
You seem to be looking to generate a string, not a date. Consider using date functions and string concatenation: you just need to substract 1 year from the current date, and then append '-01-01'
concat_ws('-', year(getdate()) - 1, '01', '01')
Demo on DB Fiddle
You basically have it. You just need the FORMAT function.
SELECT FORMAT (DATEADD(yy,-1,DATEADD(yy,DATEDIFF(yy,0,GETDATE()),0)), 'yyyy-MM-dd') as date

Convert/get varchar variable to YYYYMM

I have 4 CTE's in this table and the third one contains a DATETIME converted to VARCHAR (with format based on the requirement) as startDate in DD/MM/YYYY format. The last cte does calculations based on the data generated and one of the columns needs to store YYYYMM date based on startDate.
The problem it's getting the year and the month from this converted DATETIME, using convert() it shows this:
IDPER
-------
01/01/ --DD/MM/
These 2 show YYYYMM correctly when startDate isn't converted:
Select *, left(convert(nvarchar(6),new_ini,112),6) as IDPER from table
Select *, convert(nvarchar(6),new_ini,112) as IDPER from table
How could I get YYYYMM format having startDate converted? Or what could be a more smart approach to the requirement
If you have a string in the format DD/MM/YYYY and you want YYYYMM, then use string operations:
select right(new_ini, 4) + substring(new_ini, 4, 2)
You should be storing date values as dates or a related type, not as string. But given that you have already stored this as a string, string operations can do what you need.
My way would be slightly different
SELECT CONVERT(NVARCHAR(6), CONVERT(DATE, new_ini, 103), 112);
Here, I first converted it to date and then formatted to YYYYMMDD and taken 6 chars only
declare #date DATE = GETDATE();
select REPLACE(LEFT(CONVERT(DATE,#date,112),8),'-','') -- 1st approach
select FORMAT(#date,'yyyyMM') --2nd approach

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))

Date Conversion in SQL

I have a date in following format in my DB.
10/16 - mm/yy
I need to convert it to:
October/16
Is this possible?
If it's not possible then please tell me why.
This is not a date, it's missing the day, it's a bad way to store year/month. There should be a 4 digit year to avoid confusion and the year should be listed first to enable correct sorting, e.g. '2016/10' or a numeric value 201610.
You can cast it to a DATE first and then use a FORMAT to disply only month/year:
set dateformat myd;
select format(cast(mystupidcolumn + '/1' as date), 'MMMM/yy')
Or SUBSTR the month part and use a CASE.
try this format,
SELECT DATENAME(month, DATEADD(month, #mydate-1, CAST('2008-01-01' AS datetime)))
You can display date by using this code
select datename(month, YourColumnName) + '/' + right(YEAR(YourColumnName),2)
FROM yourTableName
Simply change yourColumnName with name of your table column and yourTableName with name of table.
Yes you can, and it depend in what database you use to call date functions
If you column Datetime format
SQL server DATENAME(Month, GETDATE())
MySQL database MONTHNAME(now())
otherwise
convert it will in your choice at database or you code logic
split the value and lookup at month enum or fake the date to be accepted and complete date format like 01/10/16
so do something like SELECT DATENAME(Month, datecolumn) + '/' + YEAR (datecolumn)
also you can use instead of Year function DATEPART(yy,datecolumn)
the way you do it with format will look like
CONVERT(VARCHAR(11),GETDATE(),106)
but excepted to get first 3 char of month JUN

Cast Function to display only the month and day from a datetime

SELECT
DateAdded,
Cast(DateAdded AS Date) AS DateAddedV1,
Cast(DateAdded AS Time) AS DateTime,
SELECT CAST(DateAdded AS Date(mm:dd) AS OrderDate
FROM Products
I am a beginner with SQL and I am trying to return the DateAdded column as OrderDate with only the month and the day but I cannot seem to get the syntax right. I appreciate anyone's assistance.
Use DatePart Function to extract day and month from Datetime type,
Select Datepart(Month,DateAdded) AS [Month], -- Month(Dateadded)
Datepart(Day,DateAdded) as [Day], -- Day(Dateadded)
..
From Products
Update: Only by using cast function you cannot extract Month and Day. If you want to keep month and day in same column
SELECT CONVERT(VARCHAR(2), Month(DateAdded)) + ':'
+ CONVERT(VARCHAR(2), Day(DateAdded))
.....
To get leading zero's use right function and to extract Time from DateAdded use Convert function with 108 value
SELECT right('0'+CONVERT(VARCHAR(2), Month(DateAdded)),2) + ':'
+ right('0'+CONVERT(VARCHAR(2), Day(DateAdded)) ,2) as [Mon:Day],
convert(varchar(10),DateAdded,108) as [Time]
.........
I think I'm working on this assignment this semester. This is what I ended up with since it HAD to be done using the CAST function:
SELECT DateAdded,
CAST(DateAdded AS date) AS DateOnly,
CAST(DateAdded AS time) AS TimeOnly,
CAST(DateAdded AS varchar(6)) MonthDay
FROM Products;
This works because varchar always has the Month the Day exactly in the first 6 characters. All the Months are 3 Characters (Jan, Feb, Mar, Apr) and then there is either a space then a 2-digit day, or 2 spaces and a 1-digit day. Either way it always adds up to 6 characters.
Here you are asking about the visible format of date/time information.
In MS SQL Server from SQ 2012 and later you can use a FORMAT()
function. If you use a version that supports this function I recommend you use it. Keep in mind that the second parameter is CASE SENSITIVE
In all versions you may use the CONVERT() function, which has
this syntax:
CONVERT ( data_type [ ( length ) ] , expression [ , style ] )
Note in paticular that style parameter (an integer) this is important if using CONVERT. A very useful reference for using either approach for display of date/time information is HERE and below is a tiny example:
SQL Fiddle demo
Query 1:
SELECT
FORMAT(SYSDATETIME(), 'MMM dd yyyy')
, CONVERT(VARCHAR(11), SYSDATETIME(), 100) -- note length set to (11)
Results:
|-------------|-------------|
| Oct 11 2015 | Oct 11 2015 |
Instead of converting, as in NoDisPlayName's answer, you could use the RTRIM functionality.
SELECT RIGHT('0' + RTRIM(MONTH(DateAdded)), 2)