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

Is this possible? Crosstab query

$
0
0

Hi All,

I have a rather complicated requirement am trying to fulfill. I'll make it simple and leave unnecessary details out. I have a table with structure similar to shown below.

DECLARE @Trans TABLE (
	trans_year int NULL,
	customer_name nvarchar(100) NULL,
	Amount FLOAT,
	Quantity FLOAT)

INSERT INTO @Trans VALUES (2010, 'ABC', 100, 200)
INSERT INTO @Trans VALUES (2011, 'ABC', 200, 100)
INSERT INTO @Trans VALUES (2012, 'ABC', 500, 100)
INSERT INTO @Trans VALUES (2013, 'ABC', 400, 700)
INSERT INTO @Trans VALUES (2014, 'ABC', 600, 800)

SELECT * FROM @Trans

What I am trying to do is, for each customer, get all the amounts across by year. And for each year, I need to add a field that can show the totaluntil that year(sort of like YTD). This code will be executed in a stored procedure and the stored procedure has two parameters called start_year and end_year. For the first year provided as the parameter, we don't need the Total column as it is going to be same as the amount for that year. Also, the quantity column is going to act like a normal column(not shown in the desired output below) and can be ignored for our discussion. Below is how the output needs to be.

Can someone please help? Thanks in advance!!

Cust20102011Total 2012Total 2013Total 2014Total 
 ABC10020030050080040012006001800


Viewing all articles
Browse latest Browse all 23857

Trending Articles



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