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

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.

Related

Sum of totals grouped by month

I've been out of the dev world for a few years so forgive me if this is a pretty basic question but I have an app that logs bookings for holiday accomodation. I want to produce a report detailing how much income per month a user gets.
My query thus far is as so:-
SELECT SUM(int_ToOwner) AS TotalIncome,
DateName(m,dtm_StartDate) AS BookingMonth
FROM tbl_Bookings
WHERE dtm_StartDate > '2021-12-31'
GROUP BY DatePart(m,dtm_StartDate), int_ToOwner, dtm_StartDate
But that produces the result below. I want it to give me a total for each month instead.
TotalIncome
BookingMonth
553.00
January
849.00
January
885.00
February
1236.00
February
1239.00
February
896.00
March
927.00
March
940.00
March
959.00
March
971.00
March
1167.00
April
1255.00
April
1500.00
April
2461.00
April
1131.00
May
1172.00
May
1275.00
May
2647.00
May
1466.00
June
1480.00
June
1496.00
June
1899.00
June
2167.00
June
1881.00
July
4990.00
July
4991.00
July
2134.00
August
4162.00
August
4883.00
August
5329.00
August
1430.00
September
1630.00
October
1130.00
November
You almost have it but you are also grouping by int_ToOwner and you have the dtm_StartDate twice.
Try:
SELECT SUM(int_ToOwner) AS TotalIncome, DateName(m,dtm_StartDate) AS BookingMonth
FROM tbl_Bookings
WHERE dtm_StartDate > '2021-12-31'
GROUP BY DatePart(m,dtm_StartDate)
A little re-format:
SELECT SUM(int_ToOwner) AS TotalIncome
, DateName(m,dtm_StartDate) AS BookingMonth
FROM tbl_Bookings
WHERE dtm_StartDate > '2021-12-31'
GROUP BY DatePart(m,dtm_StartDate)
, int_ToOwner
, dtm_StartDate
Your GROUP BY tells the database to create groups for data with equal values of
DatePart(m,dtm_StartDate)
int_ToOwner
dtm_StartDate
Then SELECT asks for each group the
calculated SUM of int_ToOwner
DateName(m,dtm_StartDate)
You should search your solution in grouping the correct attributes.

To get the Year of the previous month in 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()));

Pivot Table adding "2" to value in Report Filter

I have a file with pivot tables where the filter values are updated on a monthly basis based on the last month's date. VBA code for this:
Dim SelectDate As String
SelectDate = Worksheets("Raw").Range("A3").Value
Worksheets("Main").PivotTables("PivotTable4").PivotFields("Date").CurrentPage = SelectDate
The value in cell A3 is string based on the following function:
=A1&" "&A2
For example: January 2017
Updating the pivot tables worked fine for several months, but for this month my values no longer update correctly and after doing some investigation I realized that my pivot table has created two entries in the filter for the month January 2017 and January 20172, while November 2016 went missing:
However, when I check my underlying data, I only have one value for each month:
June 2016
February 2016
March 2016
January 2016
November 2016
December 2016
August 2016
May 2016
October 2016
July 2016
September 2016
April 2016
January 2017
February 2017
Note that when I create an new Pivot table with the same data, the filter only shows January 2017.
Any suggestions why the filter for the existing pivot table would reflect both January 2017 and January 20172?
Thanks for your help!
Here is what worked for me. This happened from what I have read elsewhere either because I added now data lines or because I did a find-and-replace. But then I changed the area of the source data in the pivot table from say
'MASTER (3)'!$A$5:$EQ$600 to 'MASTER (3)'!$A$5:$EQ$6
and then back to
'MASTER (3)'!$A$5:$EQ$600
This resolved the problem

Sorting Month And Year Results In Microsoft Access

I have the following table in Microsoft Access
TransactionDate
Market
Details
Opening
Closing
Size
Profit/Loss
I want to run a query that shows the Profit/Loss for each month.
I have been able get a query that returns the information in the following format
TransactionDate By Month Sum Of Sum Of Profit/Loss
April 2014 €1,084.99
April 2015 €674.33
April 2016 €2,057.30
August 2014 €237.59
August 2015 -€267.82
December 2014 €375.88
December 2015 -€1,161.97
February 2015 -€603.87
February 2016 -€124.71
January 2015 €75.11
January 2016 -€1,044.35
But what I want now is for it to display in chronological order as oppose to Alphabetical order.
For example
January 2014
February 2014
March 2014
etc.
I will consider that your TransactionDate field is defined as String
If you want to order by this text field in Access, you will have to use DateValue() function.
That would give:
SELECT TransactionDate FROM yourTable ORDER BY DateValue(TransactionDate)
If your field is already formatted as a Date field, then simply use order by TransactionDate to make it work.

Objective: Create Staff Turnover Report from scratch

I have a requirement to create staff turnover report that should display following information according to parameterized period:
current staff
starters
leavers
manager
contracted site
Currently, I have a few ideas how to get a report. Either create slowly changing dimension or copy snapshots of employees table for each period or track starter and leavers seperately for each payrun. I have tried slowly changing dimension and it did fine job on new starters; however, it failed on leavers. I am not sure if tracking starters and leaver for each payruns would work.
Created a table below as a start of solution
I am relatively new in MS SQL 2008 business. Please adise. The main goal is to identify managers and contracted sites with highest staff turnover.
Notes
-Currently, I am not using any specific techonlogy and looking for solution.
-I do intend to build and design a brand new database for the sake of the report. By database I mean a few collection of tables that sit on CRM database (SQL 2008). By Collection of tables I mean "dimension" table for managers, "dimension" table of contracted sites, and a table of staff. So currently, I think that my solution should have at least 3 tables; however, my skills are not that good to solve the puzzle.
I think that have tables above would let me to write a SQL query that could compare different periods and get required results.
payno depcod Idd Imported
12568 EDE322001 12568EDE322001A 31 December 2011
12568 EDE322001 12568EDE322001B 31 December 2011
16822 EDE322001 16822EDE322001A 31 December 2011
17694 EDE322001 17694EDE322001A 31 December 2011
12568 EDE322001 12568EDE322001A 04 January 2012
12568 EDE322001 12568EDE322001B 04 January 2012
16822 EDE322001 16822EDE322001A 04 January 2012
17694 EDE322001 17694EDE322001A 04 January 2012
12568 EDE322001 12568EDE322001A 31 January 2012
12568 EDE322001 12568EDE322001B 31 January 2012
16822 EDE322001 16822EDE322001A 31 January 2012
17694 EDE322001 17694EDE322001A 31 January 2012
17661 EDE322001 17661EDE322001A 31 January 2012
12568 EDE322001 12568EDE322001A 01 February 2012
12568 EDE322001 12568EDE322001B 01 February 2012
16822 EDE322001 16822EDE322001A 01 February 2012
17906 EDE322001 17906EDE322001A 01 February 2012
17907 EDE322001 17907EDE322001A 01 February 2012
12568 EDE322001 12568EDE322001A 29 February 2012
12568 EDE322001 12568EDE322001B 29 February 2012
17907 EDE322001 17907EDE322001A 29 February 2012
Table above is table of snapshots. Snapshot date is displayed in Imported Column. ( Applogoes for messy table; I could not figure out how to make a table) Now i need to find a away how to compare one date to another (ideally in the loop) to figure out the difference between 1st date and following date.
For instance, 17661 EDE322001 17661EDE322001A 31 January 2012 is a new staff and 16822 EDE322001 16822EDE322001A 01 February 2012 is a leaver.
Many thanks
I may be looking at this too simplistically given all the talk about slowly changing dimensions, etc, but what's wrong with a plain old bit of SQL? I'm going to assume you have an Employee table with Manager, ContractedSite, StartDate and EndDate fields.
You want the following:
Current staff. Is this current at the start of the period or at the end of the period or active at some time during the period?
Starters. People who have a StartDate greater than or equal to the start of the period but less than or equal to the end of the period.
Leavers. People who have an EndDate greater than or equal to the start of the period but less than or equal to the end of the period.
Turnover. Which brings us back to what you mean by "Current staff". Turnover is essentially the difference between the current staff at the start of the period and the current staff at the end of the period, expressed either as a raw number or a percentage. So current staff at the start of the period are people with a StartDate less than the period start and either no EndDate or an EndDate greater than or equal to the start of the period. Similarly with the current staff at the end of the period.
So you have some specific cases to extract from your data:
SELECT Manager, ContractedSite,
SUM(CASE WHEN StartDate < #PeriodStart AND ((EndDate IS NULL) OR (EndDate >= #PeriodStart)) THEN 1 END) AS OpeningStaff,
SUM(CASE WHEN StartDate >= #PeriodStart AND StartDate <= #PeriodEnd THEN 1 END) AS Starters,
SUM(CASE WHEN EndDate >= #PeriodStart AND EndDate <= #PeriodEnd) THEN 1 END) AS Leavers,
SUM(CASE WHEN StartDate <= #PeriodEnd AND ((EndDate IS NULL) OR (EndDate > #PeriodEnd)) THEN 1 END) AS ClosingStaff
FROM Employee
WHERE (StartDate <= #PeriodEnd) AND ((EndDate IS NULL) OR (EndDate >= #PeriodStart))
GROUP BY Manager, ContractedSite
ORDER BY Manager, ContractedSite
Now you just need to calculate the difference between OpeningStaff and ClosingStaff in your report to get the turnover and you're done.