Percentage difference from previous year - sql

Trying to add a percent difference column to my data as i'm showing the last 3 years of sales and commissions in my query and want percent of difference for each salesperson listed to show the difference in the amounts that were made for sales and also for commission from the previous year in that same month. So for the amount made in January 2017 for commission and sales, I want to show whether they had an increase or decrease in the amount between what was earned in January 2018 compared to what was earned in January 2017.
SELECT TOP (100) PERCENT
'ABC' AS CompanyCode,
ABC.AR_Salesperson.SalespersonName,
ABC.AR_SalespersonCommission.SalespersonDivisionNo,
ABC.AR_SalespersonCommission.SalespersonNo,
SUM(ABC.AR_SalespersonCommission.InvoiceTotal) AS InvoiceTotalSum,
SUM(ABC.AR_SalespersonCommission.CommissionAmt) AS CommissionAmtSum,
DATENAME(month, ABC.AR_SalespersonCommission.InvoiceDate) AS Month,
DATENAME(year, ABC.AR_SalespersonCommission.InvoiceDate) AS Year,
DATEPART(m, ABC.AR_SalespersonCommission.InvoiceDate) AS MonthNumber
FROM
ABC.AR_Customer INNER JOIN
ABC.AR_SalespersonCommission ON
ABC.AR_Customer.ARDivisionNo = ABC.AR_SalespersonCommission.ARDivisionNo AND
ABC.AR_Customer.CustomerNo = ABC.AR_SalespersonCommission.CustomerNo INNER JOIN
ABC.AR_Salesperson ON
ABC.AR_SalespersonCommission.SalespersonDivisionNo = ABC.AR_Salesperson.SalespersonDivisionNo AND
ABC.AR_SalespersonCommission.SalespersonNo = ABC.AR_Salesperson.SalespersonNo
GROUP BY
ABC.AR_Salesperson.SalespersonName,
ABC.AR_SalespersonCommission.SalespersonDivisionNo,
ABC.AR_SalespersonCommission.SalespersonNo,
DATENAME(month, ABC.AR_SalespersonCommission.InvoiceDate),
DATENAME(year, ABC.AR_SalespersonCommission.InvoiceDate),
DATEPART(m, ABC.AR_SalespersonCommission.InvoiceDate)
HAVING
(DATENAME(year, ABC.AR_SalespersonCommission.InvoiceDate) > DATEADD(year, - 4, GETDATE()))
ORDER BY
SalespersonName,
Year,
MonthNumber
Tried various ways to get the data to do this but haven't been able to, like using OVER PARTITION BY and all that. Desired Results and Sample Data are in the link below.

You can use a CTE and JOIN to it using the previous year:
; WITH L4Y
AS (SELECT TOP (100) PERCENT
'ABC' AS CompanyCode,
ABC.AR_Salesperson.SalespersonName,
ABC.AR_SalespersonCommission.SalespersonDivisionNo,
ABC.AR_SalespersonCommission.SalespersonNo,
SUM(ABC.AR_SalespersonCommission.InvoiceTotal) AS InvoiceTotalSum,
SUM(ABC.AR_SalespersonCommission.CommissionAmt) AS CommissionAmtSum,
DATENAME(month, ABC.AR_SalespersonCommission.InvoiceDate) AS Month,
DATENAME(year, ABC.AR_SalespersonCommission.InvoiceDate) AS Year,
DATEPART(m, ABC.AR_SalespersonCommission.InvoiceDate) AS MonthNumber
FROM
ABC.AR_Customer INNER JOIN
ABC.AR_SalespersonCommission ON
ABC.AR_Customer.ARDivisionNo = ABC.AR_SalespersonCommission.ARDivisionNo AND
ABC.AR_Customer.CustomerNo = ABC.AR_SalespersonCommission.CustomerNo INNER JOIN
ABC.AR_Salesperson ON
ABC.AR_SalespersonCommission.SalespersonDivisionNo = ABC.AR_Salesperson.SalespersonDivisionNo AND
ABC.AR_SalespersonCommission.SalespersonNo = ABC.AR_Salesperson.SalespersonNo
GROUP BY
ABC.AR_Salesperson.SalespersonName,
ABC.AR_SalespersonCommission.SalespersonDivisionNo,
ABC.AR_SalespersonCommission.SalespersonNo,
DATENAME(month, ABC.AR_SalespersonCommission.InvoiceDate),
DATENAME(year, ABC.AR_SalespersonCommission.InvoiceDate),
DATEPART(m, ABC.AR_SalespersonCommission.InvoiceDate)
HAVING
(DATENAME(year, ABC.AR_SalespersonCommission.InvoiceDate) > DATEADD(year, - 4, GETDATE()))
)
SELECT L4Y.*
, InvoiceTotalPrevYear = COALESCE(LY.InvoiceTotalSum, 0)
, CommissionAmtSumPrevYear = COALESCE(LY.CommissionAmtSum, 0)
FROM L4Y
LEFT JOIN L4Y LY
ON L4Y.CompanyCode = LY.CompanyCode
AND L4Y.SalespersonName = LY.SalespersonName
--...(join on ALL fields except YEAR)
AND l4y.[Month] = LY.[Month]
-- Here's where the magic happens:
AND L4Y.[Year] = (LY.[Year]-1) ;

Related

Running Totals for the year

Trying to create running totals based on the year in my query as i'm showing the last 3 years of sales and commissions in my query and want running yearly totals for those for each salesperson listed
Tried various ways to get the data to do this but haven't been able to.
SELECT TOP (100) PERCENT 'abc' AS CompanyCode, abc.AR_Salesperson.SalespersonName, abc.AR_SalespersonCommission.SalespersonDivisionNo, abc.AR_SalespersonCommission.SalespersonNo,
SUM(abc.AR_SalespersonCommission.InvoiceTotal) AS InvoiceTotalSum, SUM(abc.AR_SalespersonCommission.CommissionAmt) AS CommissionAmtSum, DATENAME(month, abc.AR_SalespersonCommission.InvoiceDate)
AS Month, DATENAME(year, abc.AR_SalespersonCommission.InvoiceDate) AS Year, DATEPART(m, abc.AR_SalespersonCommission.InvoiceDate) AS MonthNumber
FROM abc.AR_Customer INNER JOIN
abc.AR_SalespersonCommission ON abc.AR_Customer.ARDivisionNo = abc.AR_SalespersonCommission.ARDivisionNo AND abc.AR_Customer.CustomerNo = abc.AR_SalespersonCommission.CustomerNo INNER JOIN
abc.AR_Salesperson ON abc.AR_SalespersonCommission.SalespersonDivisionNo = abc.AR_Salesperson.SalespersonDivisionNo AND
abc.AR_SalespersonCommission.SalespersonNo = abc.AR_Salesperson.SalespersonNo
GROUP BY abc.AR_Salesperson.SalespersonName, abc.AR_SalespersonCommission.SalespersonDivisionNo, abc.AR_SalespersonCommission.SalespersonNo, DATENAME(month, abc.AR_SalespersonCommission.InvoiceDate),
DATENAME(year, abc.AR_SalespersonCommission.InvoiceDate), DATEPART(m, abc.AR_SalespersonCommission.InvoiceDate)
HAVING (DATENAME(year, abc.AR_SalespersonCommission.InvoiceDate) > DATEADD(year, - 3, GETDATE()))
UNION
SELECT TOP (100) PERCENT 'XYZ' AS CompanyCode, xyz.AR_Salesperson.SalespersonName, xyz.AR_SalespersonCommission.SalespersonDivisionNo, xyz.AR_SalespersonCommission.SalespersonNo,
SUM(xyz.AR_SalespersonCommission.InvoiceTotal) AS InvoiceTotalSum, SUM(xyz.AR_SalespersonCommission.CommissionAmt) AS CommissionAmtSum, DATENAME(month, xyz.AR_SalespersonCommission.InvoiceDate)
AS Month, DATENAME(year, xyz.AR_SalespersonCommission.InvoiceDate) AS Year, DATEPART(m, xyz.AR_SalespersonCommission.InvoiceDate) AS MonthNumber
FROM xyz.AR_Customer INNER JOIN
xyz.AR_SalespersonCommission ON xyz.AR_Customer.ARDivisionNo = xyz.AR_SalespersonCommission.ARDivisionNo AND xyz.AR_Customer.CustomerNo = xyz.AR_SalespersonCommission.CustomerNo INNER JOIN
xyz.AR_Salesperson ON xyz.AR_SalespersonCommission.SalespersonDivisionNo = xyz.AR_Salesperson.SalespersonDivisionNo AND
xyz.AR_SalespersonCommission.SalespersonNo = xyz.AR_Salesperson.SalespersonNo
GROUP BY xyz.AR_Salesperson.SalespersonName, xyz.AR_SalespersonCommission.SalespersonDivisionNo, xyz.AR_SalespersonCommission.SalespersonNo, DATENAME(month, xyz.AR_SalespersonCommission.InvoiceDate),
DATENAME(year, xyz.AR_SalespersonCommission.InvoiceDate), DATEPART(m, xyz.AR_SalespersonCommission.InvoiceDate)
HAVING (DATENAME(year, xyz.AR_SalespersonCommission.InvoiceDate) > DATEADD(year, - 3, GETDATE()))
I expect the output to have running totals for the InvoiceTotalSum and CommissionAmt for each salesperson for the last 3 years. So of course January will be 0 for each person but Feb through December will have a running total
Sample data and desired results below. Desired results are the highlighted columns
Sample Data and Desired Results
2 things before I go to the solution.
First, I am not sure why you need an UNION into your query. I can see the difference between abc and xyz but it still looks strange.
It is surely possible your query can be shortened/simplified, which would need more info to tell.
Second, I do not see a valid reason why the running total should be 0 for January.
Explanation about that:
February (2nd month of the year): running total in your expected result contains the amount for 2 months
March: 3 months
April: 4 months
...
So January should contain the running total for 1 month (January itself).
Try the query below:
WITH MyData AS (
<Please paste your query here>
)
SELECT CompanyCode, SalesPersonName, SalesPersonDivisionNo, InvoiceTotalSum,
SUM(InvoiceTotalSum) OVER (PARTITION BY SalesPersonDivisionNo, SalesPersonNo, SalesPersonName, Year ORDER BY MonthNumber) AS InvoiceTotalRunningSum,
CommissionAmtSum,
SUM(CommissionAmtSum) OVER (PARTITION BY SalesPersonDivisionNo, SalesPersonNo, SalesPersonName, Year ORDER BY MonthNumber) AS CommissionAmtRunningSum,
Month, Year, MonthNumber
FROM MyData
ORDER BY CompanyCode, SalesPersonDivisionNo, SalesPersonNo, SalesPersonName, Year, MonthNumber
The magic takes place in the PARTION BY/ORDER BY
I think you need to review your query and simplify it.
a few notes :
if the CompanyCode is already existed within the database, join its table and link it with the current records instead of writing it manually.
DATENAME(year, ... ) the shorthand is YEAR()
DATEPART(m, ...) the shorthand is MONTH()
I encourage you to use aliases
(DATENAME(year, xyz.AR_SalespersonCommission.InvoiceDate) > DATEADD(year, - 3, GETDATE())) will exclude the first year and include the current.So, 2019-3 = 2016, yours will get 2017,2018, and 2019, while it should get 2016,2017, and 2018.
for your InvoiceTotalRunningSum use :
SUM(InvoiceTotalSum) OVER (PARTITION BY SalespersonNo ORDER BY MonthNumber UNBOUNDED PRECEDING)
this will do an accumulative sum on InvoiceTotalSum for each SalespersonNo. you can partition the records for each year, month ..etc. simply by adding more partitions, but I used your current query as sub-query, and did that instead :
read more about SELECT - OVER Clause (Transact-SQL)
try it out :
SELECT
'abc' AS CompanyCode
, SalespersonName
, SalespersonDivisionNo
, SalespersonNo
, InvoiceTotalSum
, SUM(InvoiceTotalSum) OVER (PARTITION BY SalespersonNo ORDER BY MonthNumber UNBOUNDED PRECEDING) InvoiceTotalRunningSum
, CommissionAmtSum
, SUM(CommissionAmtSum) OVER (PARTITION BY SalespersonNo ORDER BY MonthNumber UNBOUNDED PRECEDING) CommissionAmtRunningSum
, [Month]
, [Year]
, MonthNumber
FROM (
SELECT
'abc' AS CompanyCode
, ars.SalespersonName
, arsc.SalespersonDivisionNo
, arsc.SalespersonNo
, SUM(arsc.InvoiceTotal) InvoiceTotalSum
, SUM(arsc.CommissionAmt) CommissionAmtSum
, DATENAME(month, arsc.InvoiceDate) [Month]
, YEAR(arsc.InvoiceDate) [Year]
, MONTH(arsc.InvoiceDate) MonthNumber
FROM
abc.AR_Customer arc
INNER JOIN abc.AR_SalespersonCommission arsc ON arc.ARDivisionNo = arsc.ARDivisionNo AND arc.CustomerNo = arsc.CustomerNo
INNER JOIN abc.AR_Salesperson ars ON arsc.SalespersonDivisionNo = ars.SalespersonDivisionNo AND arsc.SalespersonNo = ars.SalespersonNo
GROUP BY
ars.SalespersonName
, arsc.SalespersonDivisionNo
, arsc.SalespersonNo
, YEAR(arsc.InvoiceDate)
, MONTH(arsc.InvoiceDate)
, DATENAME(month, arsc.InvoiceDate)
HAVING
YEAR(arsc.InvoiceDate) BETWEEN YEAR(GETDATE()) - 3 AND YEAR(GETDATE()) - 1 -- Only include the last three years (excluding current year)
) D

Pivot and INNER JOINs

I have been trying to run a pivot query but I am failing hard, I am very new with all this so please be patient
what I want is to return the Quantities values of each month, jan, feb... dec, for each PartRef
this is what I have
SELECT PartRef
, Year
, fMonth
, sum(Quantity) as Quantity
FROM(SELECT PartRef
, year(DateClosed) as Year
, month(DateClosed) as Month
, SUM(fldShipped) as Quantity
FROM PartsInvoice
INNER JOIN Requests ON PartsInvoice.fID = Requests.WorkItemRef
INNER JOIN PartsLine ON Requests.ID = PartsLine.RequestRef
WHERE Closed = 1 and DateClosed > DateAdd(mm, DateDiff(mm, 0, GetDate()) -12, 0)
GROUP BY PartRef, year(DateClosed), month(DateClosed)
) as SalesHits
PIVOT (
SUM(NOT SURE)FOR NOT SURE IN ([Jan],[Feb],[Mar],[Apr],[May],[June],[July],[Ago],[Sep],[Oct],[Nov],[Dec])
)AS Hits
GROUP BY PartRef, Year, Month
Here you have an example how it works with a table like yours.
declare #table table(
partref int,
year int,
month nvarchar(50),
quantity int
)
insert into #table values
(1,2016,'jan',12),
(1,2016,'feb',12),
(2,2016,'jan',12),
(2,2016,'feb',12),
(1,2016,'jan',12)
select PartRef
, year
, sum([jan]) 'Jan',sum([feb]) 'Feb'
,sum([mar]),sum([apr]),sum([may]),sum([jun]),sum([jul])
,sum([aug]),sum([sep]),sum([oct]),sum([nov]),sum([dec])
from(
SELECT PartRef
, year
, [jan],[feb],[mar],[apr],[may],[jun],[jul],[aug],[sep],[oct],[nov],[dec]
from #table
PIVOT (
SUM(quantity)FOR month IN ([jan],[feb],[mar],[apr],[may],[jun],[jul],[aug],[sep],[oct],[nov],[dec])
)AS Hits
) as t
group by PartRef,year
here is the full scope of my query and I believe I got it to work :)
SELECT *
FROM(SELECT PartRef
, year(DateClosed) as Year
, month(DateClosed) as Month
, SUM(Shipped) as Quantity
FROM PartsInvoice
INNER JOIN Requests ON PartsInvoice.ID = Requests.WorkItemRef
INNER JOIN PartsLine ON Requests.ID = PartsLine.RequestRef
WHERE HasClosed = 1 and DateClosed > DateAdd(mm, DateDiff(mm, 0, GetDate()) -13, 0)
GROUP BY PartRef, year(DateClosed), month(DateClosed)
UNION ALL
--RO
SELECT PartRef
, year(DateClosed) as Year
, month(DateClosed) as Month
, SUM(Shipped) as Quantity
FROM RepairOrder
INNER JOIN Requests ON RepairOrder.ID = Requests.WorkItemRef
INNER JOIN PartsLine ON Requests.ID = PartsLine.RequestRef
WHERE Status = 3 and DateClosed > DateAdd(mm, DateDiff(mm, 0, GetDate()) -13, 0)
GROUP BY PartRef, year(DateClosed), month(DateClosed)
UNION ALL
-- Historical Hits
SELECT PartRef
, year(date) as Year
, month(Date) as Month
, SUM(Quantity) as Quantity
FROM PartsHistoricalHits
WHERE Date > DateAdd(mm, DateDiff(mm, 0, GetDate()) -13, 0)
GROUP BY PartRef, year(Date), month(Date)
) as SalesHits
PIVOT (
COUNT (Quantity)FOR fldMonth IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13])
)AS Hits

Average count data from pivot table - Need assistance

I am working on a little project to deliver application that pull data from database to show average of shipment made each day of the week. I have made some progress and have now script that count all of shipment but because I count them based on varchar type of column also I need solution to calculate average for each day of the week separately.
So far I end up with something as follows:
SELECT [Monday], [Tuesday], [Wednesday], [Thursday], [Friday], [Saturday], [Sunday]
FROM (
SELECT DATENAME(dw, Shipment.Date) AS DayWeek, Shipment.ID
FROM Shipment
WHERE MONTH(Shipment.Date)= MONTH(DATEADD(MONTH, DATEDIFF(MONTH, 0, 'OCTOBER 2016' ), 0)) AND
Shipment.Bur = 'GB'
) AS src
pivot (
COUNT(ID) FOR DayWeek IN ([Monday], [Tuesday], [Wednesday], [Thursday], [Friday], [Saturday], [Sunday])
) AS pvt
I appreciate much any hint or help as it is looks like I run out of ideas at the moment and can get any further to deliver right solution.
I would suggest dispensing with the pivot altogether and putting on the results in separate rows:
SELECT DayWeek, AVG(cnt)
FROM (SELECT s.Date, DATENAME(dw, s.Date) AS DayWeek, COUNT(*) as cnt
FROM Shipment s
WHERE MONTH(s.Date) = MONTH(DATEADD(MONTH, DATEDIFF(MONTH, 0, 'OCTOBER 2016' ), 0)) AND
s.Bur = 'GB'
GROUP BY s.Date
) d
GROUP BY DayWeek
ORDER BY MIN(s.Date);
I found the answer for my question by browsing through stackoverflow encountering on similar problem posted by one of the user.
SELECT [Day], SUM(q.Totals) AS "Weekly Shipment Amount", AVG(Totals) AS [Avg]
FROM
(
SELECT
w = DATEDIFF(WEEK, 0, DATE),
[Day] = DATENAME(Weekday, DATE),
Totals = COUNT(*)
FROM dbo.Shipment
--INNER JOIN FCLI (NOLOCK) ON FCLI.CCLI = FEXP.CCLI
WHERE (BUR = 'GB' AND
Shipment.Date >= '20160601' AND Shipment.Date <= '20160630')
GROUP BY
DATEDIFF(WEEK, 0, Date),
DATENAME(WEEKDAY, Date),
DATEPART(WEEKDAY, Date)
) AS q
GROUP BY [Day]
ORDER BY [DaY] ASC;

Multiple select against one table in one query

I'm trying to construct a select statement that will give me a percentage value for each month and user.
I have a table with rows that looks like this;
Table name: pytrans
tTransDate tArtCode tTime tSignature
20120801 DKK 1 30JK
20120801 AD 1.5 30JK
20120802 DKB 3 40AK
20120903 MI 2 45TR
20120904 DKK 2 30JK
20120904 DKB 2 30JK
The select(s) should give me the percentage of how much time spent on tArtCode DKB or DKK for each signature and month of all time spent on all tArtCode. So from the above example the select should give me 40% for signature 30JK in month 8 and 100% for signature 30JK in month 9.
I have tried different kind of sql select statements but It doesn’t seem to get 100% right.
This is what I’ve got;
select DATEPART(YY, tTransdatum) AS Year, DATEPART(mm, tTransdatum) AS Month, tSignatur,
(select SUM(tAntal) AS SumPart from pytrans where tSignatur = '30JK' AND (tArtikelkod = 'DKK' OR tArtikelkod = 'DKB'))
/(select DATEPART(YY, tTransdatum) AS Year, DATEPART(mm, tTransdatum) AS Month, SUM(tAntal) AS SumTot from pytrans where tSignatur = '30JK' GROUP BY Year, Month, SumTot) * 100
From pytrans where tSignatur = '30JK' GROUP BY DATEPART(mm, tTransdatum), DATEPART(YY, tTransdatum), tSignatur
This SQL don’t work the error is that I can’t group Year, Month, SumTot. Also i get error; Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
This next sql select give me what i want but I’m to specific what I’m asking for... so to speak. If I use this sql i then need to have a sql query for every signature and every month, and that’s not really creative.
select TOP 1 DATEPART(YY, tTransdatum) AS Year, DATEPART(mm, tTransdatum) AS Month, tSignatur,
SumProc = (select SUM(tAntal) from pytrans
where tSignatur = '30JK' AND (tArtikelkod NOT LIKE 'FL' AND tArtikelkod NOT LIKE 'SEM' AND tArtikelkod NOT LIKE 'KOMPIN') AND (tArtikelkod = 'DKK' OR tArtikelkod = 'DKB') AND tTransdatum BETWEEN '20121101' AND '20121131')
/ (select SUM(tAntal) from pytrans
where tSignatur = '30JK' AND (tArtikelkod NOT LIKE 'FL' AND tArtikelkod NOT LIKE 'SEM' AND tArtikelkod NOT LIKE 'KOMPIN') AND tTransdatum BETWEEN '20121101' AND '20121131') * 100
from pytrans
Where tSignatur = '30JK' AND tTransdatum BETWEEN '20121101' AND '20121131'
group by tTransdatum, tSignatur
I’ve also tried Union but that doesn’t seem to work for me.
I really need help with this! Thanks!
Create Table #pytrans(tTransdatum datetime, tArtCode varchar(10), tAntal float, tSignature varchar(10))
insert into #pytrans Values('20120801', 'DKK', 1 ,'30JK')
insert into #pytrans Values('20120801', 'AD', 1.5 ,'30JK')
insert into #pytrans Values('20120802', 'DKB', 3 ,'40AK')
insert into #pytrans Values('20120903', 'MI', 2 ,'45TR')
insert into #pytrans Values('20120904', 'DKK', 2 ,'30JK')
insert into #pytrans Values('20120904', 'DKB', 2 ,'30JK')
Select a.Year,a.Month,a.tSignature,a.SumPart as aAll,b.SumPart as bAll,Case when b.SumPart =0 then NULL else a.SumPart/b.SumPart * 100 end as [Percent]
from
(select DATEPART(YY, tTransdatum) AS Year, DATEPART(mm, tTransdatum) AS Month, tSignature
,SUM(tAntal) AS SumPart
from #pytrans
where tSignature = '30JK' AND tArtCode in( 'DKK' ,'DKB')
Group by DATEPART(YY, tTransdatum) , DATEPART(mm, tTransdatum) , tSignature) a
Left Join
(select DATEPART(YY, tTransdatum) AS Year, DATEPART(mm, tTransdatum) AS Month, tSignature
,SUM(tAntal) AS SumPart
from #pytrans
where tSignature = '30JK'
Group by DATEPART(YY, tTransdatum) , DATEPART(mm, tTransdatum) , tSignature) b
on a.Month=b.Month and a.Year =b.Year and a.tSignature = b.tSignature

How to query for a value from the last month of each quarter?

SELECT YEAR(aum.AUM_Timeperiod) as Year,
DATEPART(q, aum.AUM_TimePeriod) AS Quarter,
SUM(cast(aum.AUM_AssetValue AS money)) as total_AssetValue
FROM AssetUnderManagement as aum,
LineOfBusiness
where aum.LOB_ID = LineOfBusiness.LOB_ID
and LineOfBusiness.LOB_Name = 'Asset Management'
GROUP BY YEAR(aum.AUM_Timeperiod), DATEPART(q, aum.AUM_TimePeriod);
The above query returns the value per quarter.
My question is how to change it if I want the Total_AssetValue of the last month in that quarter to be assigned to that quarter.
For eaxmple Quater 3 total_AssetValue is sum(100+200+300). but i want the quater 3 value to be 300 which is the last month value in that quater
How about:
SELECT
Year,
Quarter,
(
SELECT SUM(CAST(AUM_AssetValue AS MONEY))
FROM AssetUnderManagement
WHERE YEAR(AUM_Timeperiod) = i.Year
AND MONTH(AUM_TimePeriod) = i.LastMonthInQuarter
) AS total_AssetValue
FROM
(
SELECT
YEAR(aum.AUM_Timeperiod) AS Year,
DATEPART(q, aum.AUM_TimePeriod) AS Quarter,
MAX(MONTH(aum.AUM_TimePeriod)) AS LastMonthInQuarter
FROM
AssetUnderManagement as aum, LineOfBusiness
WHERE
aum.LOB_ID = LineOfBusiness.LOB_ID
AND LineOfBusiness.LOB_Name = 'Asset Management'
GROUP BY
YEAR(aum.AUM_Timeperiod),
DATEPART(q, aum.AUM_TimePeriod)
) AS i
Here's a version that uses a common table expression:
WITH MyData AS
(SELECT YEAR(aum.AUM_Timeperiod) AS [Year], DATEPART(q, aum.AUM_TimePeriod) AS [Quarter],
DATEPART(M, aum.AUM_TimePeriod) AS [Month],
DATEPART(M, aum.AUM_TimePeriod) - (DATEPART(q, aum.AUM_TimePeriod) - 1) * 3 AS [MonthInQtr],
SUM(CAST(aum.AUM_AssetValue AS MONEY)) AS [total_AssetValue]
FROM AssetUnderManagement AS aum, LineOfBusiness
WHERE aum.LOB_ID = LineOfBusiness.LOB_ID
AND LineOfBusiness.LOB_Name = 'Asset Management'
GROUP BY YEAR(aum.AUM_Timeperiod), DATEPART(q, aum.AUM_TimePeriod),
DATEPART(M, aum.AUM_TimePeriod), DATEPART(M, aum.AUM_TimePeriod) -
(DATEPART(q, aum.AUM_TimePeriod) - 1) * 3
)
SELECT [Year], [Quarter]
FROM MyData
WHERE MonthInQtr = 3
ORDER BY [Year], [Quarter], [total_AssetValue]
;
You can use the same CTE from above and use the following query to get your original results
SELECT [Year], [Quarter], SUM([total_AssetValue])
FROM MyData
GROUP BY [Year], [Quarter]
ORDER BY [Year], [Quarter]
;