To get the Year of the previous month in SQL - sql

I'm trying to get the year of the previous month.
For example in July 2017 I want result 2017. But in January 2017 I want result 2016 and in Feb 2017 I want result 2017. Using SQL Server.

sql server?
select datepart(year, dateadd(month, -1, getdate()))

select year(dateadd(month,-1,GETDATE()));

Related

How can I extract last years data based on today's date

I want to extract all the data from 2016 and usually I would use:
date > DATEADD(year, -1, GETDATE())
But when I run the report in January 2018, I still want it to show me 2016 data, and when I run it again in Feb 18, it then starts showing all of 2017 data.
You could get the year -2
2018 - 2 = 2016
date > DATEADD(year,-2,GETDATE())
Subtract Month instead of Year like below :
DATEADD(month, -13, GETDATE())

Custom Sort on DimCalendar

I have a DimCalendar dimension and I want to create a custom column on top of this which will be used as a "Sort By Column" in PowerBI report.
The sorting order should be Jan 2015, Jan 2016, Jan 2017, Feb 2015, Feb 2016, Feb 2017 and so on.
Hence, can someone help me write a SQL statement to create a column which will rank the numbers in the above sorting order?
Thanks.
[UPDATE]
Sample data - I have taken only first two dates from entire month.
The customer sort can be set by using the year and month. In many databases, you can define it as:
update dimCalendar
set customsort = month(date) * 10000 + year(date);
The ANSI standard syntax would be:
update dimCalendar
set customsort = extract(month from date) * 10000 + extract(year from date);
You can concatenate year part and month part of date.
In Ms SQL server you can use
Datepart (year, date)+"/" + Datepart(month,date)

SQL to separate YYYY MM to fiscal year

I have a column which states month and year YYYY MM. I've separated those into two columns (Year and Month). The problem is, the year is the calendar year whereas ideally I need the fiscal year I use (Apr 01 to Mar 31 - This will never change).
Other solutions I've seen are based on date format, whereas my original column is string.
I need a statement that returns the fiscal year for my new year column instead of the calendar year.
My current statement is:
Select Month,
parsename(replace(Month,' ','.'),1) as MonthM,
parsename(replace(Month,' ','.'),2) as Year
FROM TblTrade
Which works to separate the columns.
So expected results would be for example:
Feb 15 becomes Feb and 2015.
Apr 15 becomes Apr and 2016.
Please advise.
Sql server:
declare #date datetime = getdate();
select
(YEAR(DATEADD(Month,-((DATEPART(Month,#date)+5) %12),#date))) AS Financial_Year
Assuming April is month 1
Try this
select case
when to_char(to_date(column_name,'yyyy mm'),'mm') between 01 and 03
then to_char(trunc(to_date(column_name,'yyyy mm')),'yyyy')-1
else to_number(to_char(trunc(to_date(column_name,'yyyy mm')),'yyyy')) end
fiscal_year
from table_name
I'm using oracle db
This will work when column is string and has valid data i.e date in format like yyyy mm
Since you've read those other articles (you should really mention what research you've done in your question) and you're still having problems, I've had a play for you.
If I understand correctly, you have a varchar with YYYY MM eg
2015 01
2015 02
2015 03
2015 04
etc And you want
Jan 2014
Feb 2014
Mar 2014
Apr 2015
Here goes...
Setup some test data
DROP TABLE IF EXISTS #Test;
WITH Dates AS (
SELECT CAST(GETDATE() AS DATE) AS Date
UNION ALL
SELECT DATEADD(MONTH, -1, Date) FROM Dates
WHERE Date > '20140101'
)
SELECT DISTINCT
CONVERT(VARCHAR(4), YEAR(Date)) + ' ' +RIGHT(CONVERT(VARCHAR(6), Date, 112), 2) YearMonth
INTO #Test
FROM Dates
OPTION (MAXRECURSION 0);
SELECT * FROM #Test
YearMonth
---------
2013 12
2014 01
2014 02
2014 03
2014 04
2014 05
etc
Find Fiscal Year
SELECT
LEFT(YEARMONTH, 4) Year
,RIGHT(YEARMONTH, 2) Month
,LEFT(DATENAME(MONTH , DateAdd( month , CONVERT(INT,RIGHT(YEARMONTH, 2)) , -1 )), 3) MonthName
,IIF(CONVERT(INT, RIGHT(YEARMONTH, 2)) >= 4, CONVERT(INT,LEFT(YEARMONTH, 4)), CONVERT(INT,LEFT(YEARMONTH, 4)-1 )) FiscalYear
FROM #TEST
Year Month MonthName FiscalYear
---- ----- --------- -----------
2013 12 Dec 2013
2014 01 Jan 2013
2014 02 Feb 2013
2014 03 Mar 2013
2014 04 Apr 2014
2014 05 May 2014
2014 06 Jun 2014
etc
You could put the year/month parsing in a sub query just to make the code cleaner and some of the nasty formatting could be replaced with FORMAT since you're on 2012.
Hope this is what you're after and helps.
Since you included the Tableau tag, I'll describe the Tableau approach -- which is a little different than the other answers since you tend to specify what you want to Tableau, and let its driver generate the necessary SQL for your database.
First, it will work best if you have a single field that has datatype DATE instead of separate fields for month and year.
You can then roll up dates to the nearest year, month, day etc (actually truncating to the beginning of the period) or extract specific parts of dates year, month, day etc as needed for grouping/display.
The added benefit of working with a true DATE datatype is that you can tell Tableau the beginning of your fiscal year for each data source, and it will sort dates appropriately. Just right click on a data source and set the date properties. You can also set the start of the week and the date format.

SQL Server 2012: How to order by year then month in chronological order

I have a simple query that averages numbers and breaks them down by year and month. The problem I am having is I can't find a way to order the results by year then month....in chronological order. Here is an example of my results;
Month Year AverageAmount
---------------------------------
April 2012 167582.1139
August 2012 206124.9323
December 2012 192481.8604
February 2012 227612.0485
January 2012 214315.2187
July 2012 195320.075
June 2012 196174.3195
March 2012 201199.9894
May 2012 190526.0571
November 2012 203441.5135
October 2012 216467.7777
September 2012 217635.9174
April 2013 206730.5333
August 2013 197296.0563
As you can see in the table above, the months are in alphabetical order... what I need is the results to be in chronological order, ie...
Month Year AverageAmount
----------------------------------
January 2012 214315.2187
February 2012 227612.0485
March 2012 201199.9894
April 2012 167582.1139
May 2012 190526.0571
June 2012 196174.3195
April 2012 206730.5333
July 2012 195320.075
August 2012 206124.9323
September 2012 217635.9174
October 2012 216467.7777
November 2012 203441.5135
December 2012 192481.8604
January 2013 187268.3027
February 2013 179755.0666
March 2013 200131.6533
Query:
SELECT
datename(month, col1) Month,
year(col2) Year,
avg(col3) AverageAmount
FROM
myDB
GROUP BY
datename(month, datefunded), year(datefunded)
ORDER BY
year(datefunded), datename(month, datefunded)
Any help would be greatly appreciated
Just use this ORDER BY:
ORDER BY
YEAR(datefunded), MONTH(datefunded)
That'll sort your data by the numerical values of year and month of that datefunded
Have a look at this answer: Convert month name to month number in SQL Server
Maybe that solves the sorting for you? You can use one of the suggestions to convert the month to a number, so that e.g. March > 3. Then you sort by that.

SQL - get last month data

I have been using this query to extract information from last month
SELECT *
FROM Member
WHERE DATEPART(m, date_created) = DATEPART(m, DATEADD(m, -1, getdate()))
with the end of the year approaching, will this automatically pull Dec 2012 when i run it in Jan 2013 ?
Yes. your getdate() function will give the current date when the query is run. And you are adding -1 to the month and comparing month of date_created column and the last month. But I think you should also do comparison of year. You should add two conditions month and year both.
Yes, it will pull December data. But it will pull December data from any year, not just 2012
Yes, it will. DATEADD is a SQL internal function that adds to the full date, not just the selected part (day, month, year).