Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Advanced query with dynamic columns

$
0
0

Hi All,

I have a table with structure shown below. I need to pull data out of this table and the output should be in a format indicated by the select statement below. I have the following questions and I appreciate if someone could help.

1. I need to extract 3 years(current year + 2 historical years) worth of data out of this table dynamically(I can't hardcode year). How can I modify the code below so that the select statement returns 3 years worth of data dynamically?

2. Should I instead calculate each quarter in the select statement using "CASE"? Would this be a good idea and i wouldn't have to deal with the PIVOT function?

3. The reason I am asking about #2 is because our application requires the out field names to be as CYQ1, CYQ2, CYQ3, CYQ4, LYQ1, LYQ2, LYQ3, LYQ4 etc.(LY = last year). I am not sure if this is possible to do in Pivot table. Could the method outlines in #2 be the best practice in my situation?

Thanks in advance for your thoughts.

DECLARE @Trans_Summary TABLE(
	[Account_ID] [int] NULL,
	[End_Date] DATE NULL,
	[Amount] [float] NULL,
	[Customer_ID] [int] NULL) 
INSERT @Trans_Summary VALUES(1, '03/31/2013', 100, 123)
INSERT @Trans_Summary VALUES( 1, '01/31/2013', 200, 123)
INSERT @Trans_Summary VALUES( 1, '06/30/2013', 100, 123)
INSERT @Trans_Summary VALUES( 1, '09/30/2013', 100, 123)
INSERT @Trans_Summary VALUES( 1, '12/31/2013', 100, 123)

SELECT *
FROM @Trans_Summary
PIVOT(SUM([Amount])FOR End_Date IN ([2013-01-31], [2013-03-31], [2013-06-30], [2013-09-30], [2013-12-31])) AS TT


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>