Let's jump straight into it. Here's the code
SELECT [prov], [201304], [201305], [201306], [201307]
FROM (
SELECT [prov], [arrival], [Amount]
FROM [tblSource]) up
PIVOT (SUM([Amount]) FOR [arrival] IN ([201304], [201305], [201306], [201307])) AS pvt
GO
It brings me back an ever so lovely table. I was wondering how I would get the totals for each "date" column to show in an appended last row?
In addition, the underlying table will have more data added, specifically more dates. This means that 201308 will be added next, then 201309 etc
This will mean that currently I will have to amend the code above each month to reflect the addition. Is there anyway around this?
You can dynamically create the columns using dynamic SQL, however, I would really recommend handling dynamic pivots in a layer designed for it, such as SSRS or excel.
This creates and executes the following SQL:
It is the query below union in the subquery
up
that adds the total row at the bottom, and the row total is simply created by adding all the columns in the row.Example on SQL Fiddle
I will stress again though, I really recommend handling manipulation of data like this outside of SQL.
EDIT
An alternative to using the UNION to get the the total row is to use
GROUPING SETS
as follows:SAMPLE TABLE
QUERY
You can use ROLLUP to get the row total. More about ROLLUP here
Note : If you do not want to replace
NULL
withzero
, just replace@NullToZeroCols
with@cols
in outer query of dynamic pivot