Year Calculation in SQL Server 2012 - sql

StartDate = 01/01/2013
EndDate = 12/31/2019
I need to get the year column like '2013-14' , '2014-15' , 2015-16 and so on.
For example, the 2013-14 year should contains date details from Jun 2013 to May 2014. Like wise i need to get the year upto End date. Please help me out.
concat(datepart(YY,StartDate ),'-', RIGHT(YEAR(StartDate ),2) + 1)
I used the above format. i can get the output as 2013-14. But i need to specify the range of month for splitting years.
Regards,
Vanmathi

Use the FORMAT function:
SELECT
FORMAT(StartDate, 'yyyy-MM'),
FORMAT(EndDate, 'yyyy-MM')
Read all about the FORMAT function on the official MSDN documentation page.

Use a user defined function to slice up the date and then text concatenation.
CREATE FUNCTION GetSlicedYear(#TheDate date)
RETURNS varchar(7)
AS
BEGIN
DECLARE #SlicedYear varchar(7)
IF DATEPART(month, #TheDate) < 6
SELECT #SlicedYear = (DATEPART(year, #TheDate) -1 ) +"-"+ RIGHT(CAST(YEAR(#TheDate) As varchar(4)),2)
ELSE
SELECT #SlicedYear = DATEPART(year, #TheDate) +"-"+ RIGHT(CAST((YEAR(#TheDate) +1) As varchar(4)),2)
RETURN #SlicedYear
END
Then something like this to Order (or group).
SELECT SomeField, GetSlicedYear(SomeDate) FROM SomeTable ORDER BY GetSlicedYear(SomeDate)

You can use the below select statement -
select FORMAT(StartDate , 'yyyy') + '-' + FORMAT(EndDate , 'yyyy')

Related

How can I get the month number (not month name) from a date in SQL Server?

How can I get the month number in sql? I use the following code but it returns the month name.
SELECT DATENAME(mm, GETDATE())
Use datepart function with m extension.
SELECT DATEPART(m, getdate())
Use the month function - SELECT MONTH(GETDATE())
Use Datepart:
DATEPART(mm,getdate());
You want DATEPART:
select datepart(mm, getdate())
You can also use this to pad the month number
SELECT RIGHT('00' + RTRIM( CAST( DATEPART( MONTH, GETDATE() ) AS varchar(2)) ) , 2)
Try the below:
SELECT DATEPART(mm,getdate())
This will return with two char in case of Jan-Sep:
SELECT CASE WHEN LEN(MONTH(GETDATE())) = 1 THEN '0' + CAST(MONTH(GETDATE()) AS VARCHAR(2))
WHEN LEN(MONTH(GETDATE())) = 2 THEN CAST(MONTH(GETDATE()) AS VARCHAR(2)) END
We can use the SQL Function: MONTH(DATE) as a parameter. It will return the month number.

SQL Server 2008 select data only between month and year

I would like select data between two date, without day
An input example:
start month: 9 , start year: 2011
end month: 3, end year: 2012
I think that there are two way to do this.
The first is convert start month and start year to date like 2011-09-01 and convert last date to 2012-03-31, but this requires calculation of the last day of end month. Obtained these date we can use a BEETWEN function for the WHERE clause (but, is the CONVERT function reliable?)
The second solution is to use the DATEPART function like in the following code:
I try to explain: if end year is equal to the initial year, then month must be between the start and end months; else if the final months is greater than the initial years if different from the initial and final year, I take everything in between; else if the final year, the month must be less than or equal to the final month, if the initial year, month must be greater than or equal to the final month
Can you help me do this in the best way? Is correct, the solution I adopted?
declare #IndDebitoCredito bit,#ProgTributo int,#mi as integer,#ai as integer,#mf as integer,#af as integer,#IDAnagrafica varchar(5)
select #mi = 01,#ai = 2011,#mf = 12,#af = 2011,#IDAnagrafica = 'DELEL',#IndDebitoCredito = 1
select distinct rrd.IDTributo
from TBWH_Delega d
--inner join TBWH_SezioneDelega sd on d.IDDelega = sd.IDDelega
inner join TBWH_Rigo rd on rd.IDDelega = d.IDDelega
inner join TBWH_RataRigo rrd on rrd.IDRigo = rd.IDRigo
where
(
DATEPART(MM,d.DataDelega)<=#mf and
DATEPART(MM,d.DataDelega)>=#mi and
DATEPART(YYYY,d.DataDelega)=#ai and
#af = #ai
)
OR
(
--anno finale magg. anno iniziale
#af > #ai AND
(
( -- delega nell'intervallo
DATEPART(YYYY,d.DataDelega)<#af AND
DATEPART(YYYY,d.DataDelega)>#ai
-- DATEPART(MM,d.DataDelega)>=#mi
)
OR
( -- delega limite destro
DATEPART(YYYY,d.DataDelega)=#af AND
DATEPART(MM,d.DataDelega)<=#mf
)
OR
( -- delega limite sinistro
DATEPART(YYYY,d.DataDelega)=#ai AND
DATEPART(MM,d.DataDelega)>=#mi
)
)
)
GO
Your first solution is almost there, but is more complicated than it needs to be and won't work anyway. It will miss out any rows from the last day of the end month.
You can add one month to the end month and then use BETWEEN on the first of each month. eg.
start month: 9 , start year: 2011
end month: 3, end year: 2012
BETWEEN '2011-09-01' AND '2012-04-01'
or, as JNK points out, this will be better:
DataDelega >= '2011-09-01' AND DataDelega < '2012-04-01'
You'll need to add in some logic to deal with the end month being December, but this looks like the simplest way of doing it.
You are WAY overcomplicating this. You really only need two comparisons:
Is the month and year after or equal to the initial value?
Is the month and year before or equal to the final value?
Try:
SELECT *
FROM MyTable
WHERE Datefield BETWEEN
CAST(#mi as varchar) + '/1/' + CAST(#ai as varchar)
-- first of first month
AND
DATEADD(DAY, -1, (DATEADD(Month, + 1, (CAST(#mf as varchar) + '/1/' + CAST(#af as varchar)))))
-- Last day or final month
SELECT *
FROM Table
WHERE DateField
BETWEEN CONVERT(DATE, CONVERT(CHAR(4), #ai) + RIGHT('00' + CONVERT(VARCHAR(2), #mi), 2) + '01', 112)
AND DATEADD(DD, -1, DATEADD(MM, 1, CONVERT(DATE, CONVERT(CHAR(4), #af) + RIGHT('00' + CONVERT(VARCHAR(2), #mf), 2) + '01', 112)))
Avoid using expressions on the DateField columns, as it makes query not SARGable.
I would use:
WHERE DateToCheck >= --- first day of StartMonth
DATEADD( mm, #StartMonth-1,
DATEADD( yy, #StartYear-2000, '2000-01-01')
)
AND DateToCheck < --- first day of next month (after EndMonth)
DATEADD( mm, #EndMonth,
DATEADD( yy, #EndYear-2000, '2000-01-01')
)
DECLARE #mi INT
, #ai INT
, #mf INT
, #af INT
SELECT #mi = 01
, #ai = 2011
, #mf = 12
, #af = 2011
--local variables to hold dates
DECLARE #i DATETIME
, #f DATETIME
--build strings to represent dates in YYYYMMDD format
--add a month to the #f date
SELECT #i = CONVERT(VARCHAR(4), #ai) + RIGHT('0' + CONVERT(VARCHAR(2), #mi),
2) + '01'
, #f = DATEADD(month, 1,
CONVERT(VARCHAR(4), #af) + RIGHT('0'
+ CONVERT(VARCHAR(2), #mf),
2) + '01')
--select data where date >= #i, and < #f
SELECT *
FROM MyTable
WHERE DateField >= #i
AND DateField < #f

Most efficient way to calculate the first day of the current Financial Year?

What's the most efficient way to calculate the first day of the current (Australian) Financial Year?
The Australian FY begins on 01-July.
E.g.
SELECT dbo.FinancialYearStart('30-Jun-2011') returns 01-Jul-2010.
SELECT dbo.FinancialYearStart('01-Jul-2011') returns 01-Jul-2011.
SELECT dbo.FinancialYearStart('02-Jul-2011') returns 01-Jul-2011.
One DATEADD, one DATEDIFF, and a division:
SELECT DATEADD(year,DATEDIFF(month,'19010701','20110630')/12,'19010701')
Basically, you count the number of months since some arbitrary financial year's start date (I've picked 1901), divide that number by 12 (ignoring the remainder), and add that many years back to the same arbitrary year's start date.
I don't know if this is the most efficient, but it's fast at least...
create function dbo.FinancialYearStart
(
#CurrentDate datetime
)
returns datetime
as
begin
declare #CurrentYear int
,#FYDateThisYear datetime
,#FYDatePrevYear datetime
set #CurrentYear = datepart(year, #CurrentDate)
set #FYDateThisYear = '01-Jul-' + cast(#CurrentYear as varchar(4))
set #FYDatePrevYear = '01-Jul-' + cast(#CurrentYear-1 as varchar(4))
if #CurrentDate < #FYDateThisYear
begin
return #FYDatePrevYear
end
return #FYDateThisYear
end
Extract the year and month from the date. Then do year = year + FLOOR((month-7) / 6)
Then your date is 1-jul-year
(You don't actually need to store them as variables.)
Something like: CONCATENATE('01-jul-', YEAR(date) + FLOOR((MONTH(date)-7) / 6)
A somewhat sophisticated method (maybe a tiny little bit too much):
SELECT
DATEADD(month,
(MONTH(GETDATE()) - 1) / 6 * 12 - 6,
CAST(CAST(YEAR(GETDATE()) AS varchar) AS datetime)
)
Clunky but it works
select
cast('01-Apr-' +
cast(
case
when datepart(mm,getdate()) in (4,5,6,7,8,9,10,11,12)
then DATEPART(yy,getdate())
else DATEPART(yy,getdate())-1
end as varchar
) as datetime
) as fy_start
SELECT cast(cast(YEAR(getdate())-
(case
when MONTH(GETDATE()) between 1 and 6 then 1
else 0
end) as varchar)+'0701' as date)

Convert Month Number to Month Name Function in SQL

I have months stored in SQL Server as 1,2,3,4,...12. I would like to display them as January,February etc. Is there a function in SQL Server like MonthName(1) = January? I am trying to avoid a CASE statement, if possible.
I think this is the best way to get the month name when you have the month number
Select DateName( month , DateAdd( month , #MonthNumber , 0 ) - 1 )
Or
Select DateName( month , DateAdd( month , #MonthNumber , -1 ) )
A little hacky but should work:
SELECT DATENAME(month, DATEADD(month, #mydate-1, CAST('2008-01-01' AS datetime)))
SELECT DATENAME(month, GETDATE()) AS 'Month Name'
SUBSTRING('JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC ', (#intMonth * 4) - 3, 3)
Use the Best way
Select DateName( month , DateAdd( month , #MonthNumber , -1 ))
It is very simple.
select DATENAME(month, getdate())
output : January
Starting with SQL Server 2012, you can use FORMAT and DATEFROMPARTS to solve this problem. (If you want month names from other cultures, change: en-US)
select FORMAT(DATEFROMPARTS(1900, #month_num, 1), 'MMMM', 'en-US')
If you want a three-letter month:
select FORMAT(DATEFROMPARTS(1900, #month_num, 1), 'MMM', 'en-US')
If you really want to, you can create a function for this:
CREATE FUNCTION fn_month_num_to_name
(
#month_num tinyint
)
RETURNS varchar(20)
AS
BEGIN
RETURN FORMAT(DATEFROMPARTS(1900, #month_num, 1), 'MMMM', 'en-US')
END
You can use the inbuilt CONVERT function
select CONVERT(varchar(3), Date, 100) as Month from MyTable.
This will display first 3 characters of month (JAN,FEB etc..)
in addition to original
SELECT DATENAME(m, str(2) + '/1/2011')
you can do this
SELECT DATENAME(m, str([column_name]) + '/1/2011')
this way you get names for all rows in a table. where [column_name] represents a integer column containing numeric value 1 through 12
2 represents any integer, by contact string i created a date where i can extract the month. '/1/2011' can be any date
if you want to do this with variable
DECLARE #integer int;
SET #integer = 6;
SELECT DATENAME(m, str(#integer) + '/1/2011')
In some locales like Hebrew, there are leap months dependant upon the year so to avoid errors in such locales you might consider the following solution:
SELECT DATENAME(month, STR(YEAR(GETDATE()), 4) + REPLACE(STR(#month, 2), ' ', '0') + '01')
The following works for me:
CAST(GETDATE() AS CHAR(3))
Use this statement to convert Month numeric value to Month name.
SELECT CONVERT(CHAR(3), DATENAME(MONTH, GETDATE()))
Just subtract the current month from today's date, then add back your month number. Then use the datename function to give the full name all in 1 line.
print datename(month,dateadd(month,-month(getdate()) + 9,getdate()))
Sure this will work
select datename(M,GETDATE())
SELECT DateName(M, DateAdd(M, #MONTHNUMBER, -1))
To convert month number to month name, try the below
declare #month smallint = 1
select DateName(mm,DATEADD(mm,#month - 1,0))
You can use the convert functin as below
CONVERT(VARCHAR(3), DATENAME(MM, GETDATE()), 100)
i think this is enough to get month name when u have date.
SELECT DATENAME(month ,GETDATE())
SELECT DATENAME(MONTH,dateadd(month, -3,getdate()))
This one worked for me:
#MetricMonthNumber (some number)
SELECT
(DateName( month , DateAdd( month , #MetricMonthNumber - 1 , '1900-01-01' ) )) AS MetricMonthName
FROM TableName
From a post above from #leoinfo and #Valentino Vranken. Just did a quick select and it works.
Declare #MonthNumber int
SET #MonthNumber=DatePart(Month,GETDATE())
Select DateName( month , DateAdd( month , #MonthNumber , 0 ) - 1 )
Explaination:
First Decalre Variable MonthNumber
Get Current Month for DatePart which Return Month Number
Third Query Return Month Name
select monthname(curdate());
OR
select monthname('2013-12-12');
Working for me
SELECT MONTHNAME(<fieldname>) AS "Month Name" FROM <tablename> WHERE <condition>
you can get the date like this.
eg:- Users table
id name created_at
1 abc 2017-09-16
2 xyz 2017-06-10
you can get the monthname like this
select year(created_at), monthname(created_at) from users;
output
+-----------+-------------------------------+
| year(created_at) | monthname(created_at) |
+-----------+-------------------------------+
| 2017 | september |
| 2017 | june |
You can create a function like this to generate the Month and do
SELECT dbo.fn_GetMonthFromDate(date_column) as Month FROM table_name
/****** Object: UserDefinedFunction [dbo].[fn_GetMonthFromDate] Script Date: 11/16/2018 10:26:33 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[fn_GetMonthFromDate]
(#date datetime)
RETURNS varchar(50)
AS
BEGIN
DECLARE #monthPart int
SET #monthPart = MONTH(#date)
IF #monthPart = 1
BEGIN
RETURN 'January'
END
ELSE IF #monthPart = 2
BEGIN
RETURN 'February'
END
ELSE IF #monthPart = 3
BEGIN
RETURN 'March'
END
ELSE IF #monthPart = 4
BEGIN
RETURN 'April'
END
ELSE IF #monthPart = 5
BEGIN
RETURN 'May'
END
ELSE IF #monthPart = 6
BEGIN
RETURN 'June'
END
ELSE IF #monthPart = 7
BEGIN
RETURN 'July'
END
ELSE IF #monthPart = 8
BEGIN
RETURN 'August'
END
ELSE IF #monthPart = 9
BEGIN
RETURN 'September'
END
ELSE IF #monthPart = 10
BEGIN
RETURN 'October'
END
ELSE IF #monthPart = 11
BEGIN
RETURN 'November'
END
ELSE IF #monthPart = 12
BEGIN
RETURN 'December'
END
RETURN NULL END
Here is my solution using some information from others to solve a problem.
datename(month,dateadd(month,datepart(month,Help_HelpMain.Ticket_Closed_Date),-1)) as monthname
There is no system defined function in SQL server. But you can create your own user-defined function- a scalar function. You would find scalar functions in the Object Explorer for your database: Programmability->Functions->Scalar-valued Functions. Below, I use a table variable to bring it all together.
--Create the user-defined function
CREATE FUNCTION getmonth (#num int)
RETURNS varchar(9) --since 'September' is the longest string, length 9
AS
BEGIN
DECLARE #intMonth Table (num int PRIMARY KEY IDENTITY(1,1), month varchar(9))
INSERT INTO #intMonth VALUES ('January'), ('February'), ('March'), ('April'), ('May')
, ('June'), ('July'), ('August') ,('September'), ('October')
, ('November'), ('December')
RETURN (SELECT I.month
FROM #intMonth I
WHERE I.num = #num)
END
GO
--Use the function for various months
SELECT dbo.getmonth(4) AS [Month]
SELECT dbo.getmonth(5) AS [Month]
SELECT dbo.getmonth(6) AS [Month]
to_char(to_date(V_MONTH_NUM,'MM'),'MONTH')
where V_MONTH_NUM is the month number
SELECT to_char(to_date(V_MONTH_NUM,'MM'),'MONTH') from dual;
Use this statement for getting month name:
DECLARE #date datetime
SET #date='2015/1/4 00:00:00'
SELECT CAST(DATENAME(month,#date ) AS CHAR(3))AS 'Month Name'
This will give you short month name. Like this: Jan, Feb, Mar, etc.
Try this: SELECT MONTHNAME(concat('1970-',[Month int val],'-01'))
For example- SELECT MONTHNAME(concat('1970-',4,'-01'))
The answer is - April

Get month and year from a datetime in SQL Server 2005

I need the month+year from the datetime in SQL Server like 'Jan 2008'. I'm grouping the query by month, year. I've searched and found functions like datepart, convert, etc., but none of them seem useful for this. Am I missing something here? Is there a function for this?
select
datepart(month,getdate()) -- integer (1,2,3...)
,datepart(year,getdate()) -- integer
,datename(month,getdate()) -- string ('September',...)
If you mean you want them back as a string, in that format;
SELECT
CONVERT(CHAR(4), date_of_birth, 100) + CONVERT(CHAR(4), date_of_birth, 120)
FROM customers
Here are the other format options
Beginning with SQL Server 2012, you can use:
SELECT FORMAT(#date, 'yyyyMM')
Use:
select datepart(mm,getdate()) --to get month value
select datename(mm,getdate()) --to get name of month
In SQL server 2012, below can be used
select FORMAT(getdate(), 'MMM yyyy')
This gives exact "Jun 2016"
Funny, I was just playing around writing this same query out in SQL Server and then LINQ.
SELECT
DATENAME(mm, article.Created) AS Month,
DATENAME(yyyy, article.Created) AS Year,
COUNT(*) AS Total
FROM Articles AS article
GROUP BY
DATENAME(mm, article.Created),
DATENAME(yyyy, article.Created)
ORDER BY Month, Year DESC
It produces the following ouput (example).
Month | Year | Total
January | 2009 | 2
How about this?
Select DateName( Month, getDate() ) + ' ' + DateName( Year, getDate() )
That format doesn't exist. You need to do a combination of two things,
select convert(varchar(4),getdate(),100) + convert(varchar(4),year(getdate()))
( Month(Created) + ',' + Year(Created) ) AS Date
the best way to do that is with :
dateadd(month,datediff(month,0,*your_date*),0)
it will keep your datetime type
cast(cast(sq.QuotaDate as date) as varchar(7))
gives "2006-04" format
The question is about SQL Server 2005, many of the answers here are for later version SQL Server.
select convert (varchar(7), getdate(),20)
--Typical output 2015-04
SQL Server 2005 does not have date function which was introduced in SQL Server 2008
returns the full month name, -, full year e.g. March-2017
CONCAT(DATENAME(mm, GetDate()), '-', DATEPART(yy, GetDate()))
I had the same problem and after looking around I found this:
SELECT DATENAME(yyyy, date) AS year
FROM Income
GROUP BY DATENAME(yyyy, date)
It's working great!
Converting the date to the first of the month allows you to Group By and Order By a single attribute, and it's faster in my experience.
declare #mytable table(mydate datetime)
declare #date datetime
set #date = '19000101'
while #date < getdate() begin
insert into #mytable values(#date)
set #date = dateadd(day,1,#date)
end
select count(*) total_records from #mytable
select dateadd(month,datediff(month,0,mydate),0) first_of_the_month, count(*) cnt
from #mytable
group by dateadd(month,datediff(month,0,mydate),0)
---Lalmuni Demos---
create table Users
(
userid int,date_of_birth date
)
---insert values---
insert into Users values(4,'9/10/1991')
select DATEDIFF(year,date_of_birth, getdate()) - (CASE WHEN (DATEADD(year, DATEDIFF(year,date_of_birth, getdate()),date_of_birth)) > getdate() THEN 1 ELSE 0 END) as Years,
MONTH(getdate() - (DATEADD(year, DATEDIFF(year, date_of_birth, getdate()), date_of_birth))) - 1 as Months,
DAY(getdate() - (DATEADD(year, DATEDIFF(year,date_of_birth, getdate()), date_of_birth))) - 1 as Days,
from users
Yes, you can use datename(month,intime) to get the month in text.
,datename(month,(od.SHIP_DATE)) as MONTH_
Answer:
MONTH_
January
January
September
October
December
October
September
It's work great.
DECLARE #pYear VARCHAR(4)
DECLARE #pMonth VARCHAR(2)
DECLARE #pDay VARCHAR(2)
SET #pYear = RIGHT(CONVERT(CHAR(10), GETDATE(), 101), 4)
SET #pMonth = LEFT(CONVERT(CHAR(10), GETDATE(), 101), 2)
SET #pDay = SUBSTRING(CONVERT(CHAR(10), GETDATE(), 101), 4,2)
SELECT #pYear,#pMonth,#pDay
The following works perfectly! I just used it, try it out.
date_format(date,'%Y-%c')