Solved

SQL for monthly balance change

Posted on 2016-10-06
15
61 Views
Last Modified: 2016-10-20
Working with a table that has a data as shown below. How do I write a T-SQL statement that shows the monthly change in balance over 12 consecutive months? Thanks.

PERIOD      AVG_MTD_ACTL
201501      $19,833,568.74
201502      $20,545,226.37
201503      $20,207,922.27
201504      $20,275,581.84
201505      $20,220,454.21
201506      $20,213,055.00
201507      $20,232,099.51
201508      $20,250,648.82
201509      $20,248,825.95
201510      $20,224,476.03
201511      $19,905,864.93
201512      $20,503,382.87
0
Comment
Question by:saved4use
  • 5
  • 4
  • 3
  • +2
15 Comments
 
LVL 35

Expert Comment

by:Terry Woods
ID: 41832844
Do you mean a single dollar value that is the difference between a given month and a year before that?
0
 
LVL 17

Expert Comment

by:Pawan Kumar Khowal
ID: 41832845
Hi,

Pls try this... If you need something different , please provide output expected. Thanks

--

CREATE TABLE tryqw
(
	 PERIOD BIGINT
	,AVG_MTD_ACTL NUMERIC(25,2)
)
GO

INSERT INTO tryqw VALUES
(201501,      19833568.74),
(201502,      20545226.37),
(201503,      20207922.27),
(201504,      20275581.84),
(201505,      20220454.21),
(201506,      20213055.00),
(201507,      20232099.51),
(201508,      20250648.82),
(201509,      20248825.95),
(201510,      20224476.03),
(201511,      19905864.93),
(201512,      20503382.87)
GO

;WITH CTE AS
(
       SELECT * , DATEFROMPARTS( LEFT(PERIOD,4) ,  RIGHT(PERIOD,2) , '01' ) dt FROM tryqw
)
,CTE1 AS
(
       SELECT a.PERIOD , a.AVG_MTD_ACTL , ISNULL(qw.MonthySumChange,0) MonthySumChange FROM CTE a	  
       CROSS APPLY
       (
             SELECT SUM(b.AVG_MTD_ACTL) MonthySumChange 
             FROM CTE b
             WHERE b.dt BETWEEN DATEADD(M,-11,a.dt) AND DATEADD(M,-1,a.dt)
       )qw
	   
)
SELECT * FROM CTE1


--

Open in new window

0
 
LVL 17

Expert Comment

by:Pawan Kumar Khowal
ID: 41832901
Or may be you need this.

--




CREATE TABLE tryqw
(
	 PERIOD BIGINT
	,AVG_MTD_ACTL NUMERIC(25,2)
)
GO

INSERT INTO tryqw VALUES
(201501,      19833568.74),
(201502,      20545226.37),
(201503,      20207922.27),
(201504,      20275581.84),
(201505,      20220454.21),
(201506,      20213055.00),
(201507,      20232099.51),
(201508,      20250648.82),
(201509,      20248825.95),
(201510,      20224476.03),
(201511,      19905864.93),
(201512,      20503382.87)
GO

;WITH CTE AS
(
       SELECT * , DATEFROMPARTS( LEFT(PERIOD,4) ,  RIGHT(PERIOD,2) , '01' ) dt FROM tryqw
)
,CTE1 AS
(
       SELECT a.PERIOD , a.AVG_MTD_ACTL , ISNULL(qw.MonthySumChange,0) MonthySumChange FROM CTE a	  
       CROSS APPLY
       (
             SELECT SUM(b.AVG_MTD_ACTL) MonthySumChange 
             FROM CTE b
             WHERE b.dt = DATEADD(M,-11,a.dt)
       )qw
	   
)
SELECT * FROM CTE1

--

Open in new window

0
 
LVL 45

Expert Comment

by:Vitor Montalvão
ID: 41833496
Since the period is by year and you have YYYYMM a good trick is to cast it to int and compare with the previous year so you can have the balance result:
SELECT t2.PERIOD, t2.AVG_MTD_ACTL-t1.AVG_MTD_ACTL Balance
FROM tblName t1
	INNER JOIN tblName t2 ON CAST(T2.PERIOD AS INT)-1=CAST(t1.PERIOD AS INT)

Open in new window

0
 
LVL 69

Expert Comment

by:ScottPletcher
ID: 41834098
Which version of SQL Server?  In particular, SQL 2012 and later or before SQL 2012?
0
 

Author Comment

by:saved4use
ID: 41834171
SQL 2008.
0
 
LVL 69

Expert Comment

by:ScottPletcher
ID: 41834207
What result do you want to see for, say, the first three rows?

PERIOD      AVG_MTD_ACTL  ?monthly change in balance?
201501      $19,833,568.74   ?
201502      $20,545,226.37   ?
201503      $20,207,922.27   ?
0
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 

Author Comment

by:saved4use
ID: 41834302
The balance difference between 201502 and 201501, followed by the difference between 201503 and 201502 and so forth. Basically the monthly increase/decrease spit out in another column.
Thank you.
0
 
LVL 69

Expert Comment

by:ScottPletcher
ID: 41834344
SELECT t.PERIOD, t.AVG_MTD_ACTL, t.AVG_MTD_ACTL - t_previous.AVG_MTD_ACTL
FROM tryqw t
LEFT OUTER JOIN tryqw t_previous ON t_previous.PERIOD = t.PERIOD - 1
0
 
LVL 17

Expert Comment

by:Pawan Kumar Khowal
ID: 41834562
Here is the entire code you need

CREATE TABLE tryqw
(
	 PERIOD BIGINT
	,AVG_MTD_ACTL NUMERIC(25,2)
)
GO

INSERT INTO tryqw VALUES
(201501,      19833568.74),
(201502,      20545226.37),
(201503,      20207922.27),
(201504,      20275581.84),
(201505,      20220454.21),
(201506,      20213055.00),
(201507,      20232099.51),
(201508,      20250648.82),
(201509,      20248825.95),
(201510,      20224476.03),
(201511,      19905864.93),
(201512,      20503382.87)
GO

Open in new window


Solution

--


;WITH CTE AS
(
       SELECT * , DATEFROMPARTS( LEFT(PERIOD,4) ,  RIGHT(PERIOD,2) , '01' ) dt FROM tryqw
)
,CTE1 AS
(
      SELECT a.PERIOD , a.AVG_MTD_ACTL ,  a.AVG_MTD_ACTL - ISNULL(LAG(AVG_MTD_ACTL) OVER (ORDER BY dt), AVG_MTD_ACTL) Differences FROM CTE a	        
)
SELECT * FROM CTE1

--

Open in new window


OUPTUT

Output..
Enjoy !!
1
 
LVL 45

Expert Comment

by:Vitor Montalvão
ID: 41836449
saved4use, can you at least give a feedback on the solutions that the Experts gave?
If not working please let us know the error for further investigation.
Cheers
0
 

Author Comment

by:saved4use
ID: 41839214
@Pawan, your last solution is close to perfect. However, can it be optimized for SQL Server 2008? Apparently, functions like LAG and DATEFROMPARTS are compatible with SQL Server 2012/16?
Thank you for your tremendous assistance.

"Msg 195, Level 15, State 10, Line 3
'LAG' is not a recognized built-in function name."
0
 
LVL 17

Accepted Solution

by:
Pawan Kumar Khowal earned 500 total points
ID: 41839543
Pls try this.. I

--

;WITH CTE AS
(
       SELECT * , CAST( (LEFT(PERIOD,4) +  RIGHT(PERIOD,2) + '01') AS DATE ) dt FROM tryqw
)
SELECT a.PERIOD , a.AVG_MTD_ACTL, a.AVG_MTD_ACTL - ISNULL(bn,a.AVG_MTD_ACTL) Differences FROM CTE a
OUTER APPLY
(
      SELECT TOP 1 b.AVG_MTD_ACTL bn
	  FROM CTE b      
	  WHERE a.dt > b.dt
	  ORDER BY b.dt DESC
)t


--

Open in new window

1
 

Author Closing Comment

by:saved4use
ID: 41842639
Excellent and perfect! Thank you!
0
 

Author Comment

by:saved4use
ID: 41851191
@Pawan

How do I modify the above code snippet to make a table or select the average of the Differences column?
I have tried the below and keep getting the following error prompts:

Msg 102, Level 15, State 1, Line 3
Incorrect syntax near ';'.
Msg 102, Level 15, State 1, Line 14
Incorrect syntax near ')'.

select avg(Differences) as Avg_Diff

from (;WITH CTE AS
(
       SELECT * , CAST( (LEFT(PERIOD,4) +  RIGHT(PERIOD,2) + '01') AS DATE ) dt FROM tryqw
)
SELECT a.PERIOD , a.AVG_MTD_ACTL, a.AVG_MTD_ACTL - ISNULL(bn,a.AVG_MTD_ACTL) Differences FROM CTE a
OUTER APPLY
(
      SELECT TOP 1 b.AVG_MTD_ACTL bn
        FROM CTE b      
        WHERE a.dt > b.dt
        ORDER BY b.dt DESC
)t)

Thank you for your tremendous assistance.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Composite queries are used to retrieve the results from joining multiple queries after applying any filters. UNION, INTERSECT, MINUS, and UNION ALL are some of the operators used to get certain desired results.​
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now