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

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)

Related

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

Need part of a date

I am using SQL Server 2008R2.
I am trying to get part of a date in an output, and my column is in datetime datatype.
Eg,
If Current date and time is 2016-06-28 17:34:12.060, then I need output as 17:00 only the Hour with :00 mins.
I have tried this until now,
Select DateName(HH,SUBSTRING('2016-06-28 17:34:12.060',12,5)) +':00'
which gives me right output.But when I pass Column Name which is of datetime datatype, then it gives error,
Select DateName(HH,SUBSTRING(TimeInHour,12,5)) +':00'
gives error,
Argument data type time is invalid for argument 1 of substring function.
I know I am using SUBSTRING() at wrong place, But I really don't know how to achieve that output.
A help will be much appreciable.I need output as HH:00, Hour will be anything but 00 mins.
Why would you use substring() at all? The second argument to datename() should be a date/time data type. So, just do:
Select DateName(hour, '2016-06-28 17:34:12.060') + ':00'
Try this:
Select CAST(DATEPART(hour,'2016-06-28 17:34:12.060') AS VARCHAR(2)) +':00'
Below is the code that might be helpful
SELECT CONVERT(VARCHAR(50),DATEPART(YY,'2016-06-28 17:34:12.060')) -- Year
SELECT CONVERT(VARCHAR(50),DATEPART(mm,'2016-06-28 17:34:12.060')) -- Month
SELECT CONVERT(VARCHAR(50),DATEPART(d,'2016-06-28 17:34:12.060')) -- Day
SELECT CONVERT(VARCHAR(50),DATEPART(HH,'2016-06-28 17:34:12.060'))+':00' -- Hour
SELECT CONVERT(VARCHAR(50),DATEPART(mi,'2016-06-28 17:34:12.060'))+':00' -- Minutes
SELECT CONVERT(VARCHAR(50),DATEPART(ss,'2016-06-28 17:34:12.060')) -- Seconds
SELECT CONVERT(VARCHAR(50),DATEPART(ms,'2016-06-28 17:34:12.060')) -- Millisecond
You need to cast your DATETIME type column first, Use CAST function
Select DateName(HH,SUBSTRING(CAST(ColumnName AS VARCHAR(30)),12,5)) +':00'
Or alternative to do is Use LEFT and CONVERT
SELECT LEFT(CONVERT(VARCHAR, ColumnName ,108),2)+':00'
select convert(varchar, datepart(hour, getdate())) + ':' + convert(varchar, datepart(second, getdate()))

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

Date arithmetic in SQL on DB2/ODBC

I'm building a query against a DB2 database, connecting through the IBM Client Access ODBC driver. I want to pull fields that are less than 6 days old, based on the field 'a.ofbkddt'... the problem is that this field is not a date field, but rather a DECIMAL field, formatted as YYYYMMDD.
I was able to break down the decimal field by wrapping it in a call to char(), then using substr() to pull the year, month and day fields. I then formatted this as a date, and called the days() function, which gives a number that I can perform arithmetic on.
Here's an example of the query:
select
days( current date) -
days( substr(char(a.ofbkddt),1,4) concat '-' -- YYYY-
concat substr(char(a.ofbkddt),5,2) concat '-' -- MM-
concat substr(char(a.ofbkddt),7,2) ) as difference, -- DD
a.ofbkddt as mydate
from QS36F.ASDF a
This yields the following:
difference mydate
2402 20050402
2025 20060306
...
4 20110917
3 20110918
2 20110919
1 20110920
This is what I expect to see... however when I use the same logic in the where clause of my query:
select
days( current date) -
days( substr(char(a.ofbkddt),1,4) concat '-' -- YYYY-
concat substr(char(a.ofbkddt),5,2) concat '-' -- MM-
concat substr(char(a.ofbkddt),7,2) ) as difference, -- DD
a.ofbkddt as mydate
from QS36F.ASDF a
where
(
days( current date) -
days( substr(char(a.ofbkddt),1,4) concat '-' -- YYYY-
concat substr(char(a.ofbkddt),5,2) concat '-' -- MM
concat substr(char(a.ofbkddt),7,2) ) -- DD
) < 6
I don't get any results back from my query, even though it's clear that I am getting date differences of as little as 1 day (obviously less than the 6 days that I'm requesting in the where clause).
My first thought was that the return type of days() might not be an integer, causing the comparison to fail... according to the documentation for days() found at http://publib.boulder.ibm.com/iseries/v5r2/ic2924/index.htm?info/db2/rbafzmst02.htm, it returns a bigint. I cast the difference to integer, just to be safe, but this had no effect.
You're going about this backwards. Rather than using a function on every single value in the table (so you can compare it to the date), you should pre-compute the difference in the date. It's costing you resources to run the function on every row - you'd save a lot if you could just do it against CURRENT_DATE (it'd maybe save you even more if you could do it in your application code, but I realize this might not be possible). Your dates are in a sortable format, after all.
The query looks like so:
SELECT ofbkddt as myDate
FROM QS36F.ASDF
WHERE myDate > ((int(substr(char(current_date - 6 days, ISO), 1, 4)) * 10000) +
(int(substr(char(current_date - 6 days, ISO), 6, 2)) * 100) +
(int(substr(char(current_date - 6 days, ISO), 9, 2))))
Which, when run against your sample datatable, yields the following:
myDate
=============
20110917
20110918
20110919
20110920
You might also want to look into creating a calendar table, and add these dates as one of the columns.
What if you try a common table expression?
WITH A AS
(
select
days( current date) -
days( substr(char(a.ofbkddt),1,4) concat '-' -- YYYY-
concat substr(char(a.ofbkddt),5,2) concat '-' -- MM-
concat substr(char(a.ofbkddt),7,2) ) as difference, -- DD
a.ofbkddt as mydate
from QS36F.ASDF a
)
SELECT
*
FROM
a
WHERE
difference < 6
Does your data have some nulls in a.ofbkddt? Maybe this is causing some funny behaviour in how db2 is evaluating the less than operation.