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

SQL pivot - how do I pivot two columns of data?

$
0
0

I've had a look at similar questions asked but none of the answers seems to fit what I'm trying to achieve.

My existing code (with sample tables) is:

CREATE TABLE [dbo].[CashDetail](
	[MappingMenu] [nchar](10) NULL,
	[CreatedOn] [datetime] NULL,
	[Value] [money] NULL,
	[Narrative] [nvarchar](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

CREATE TABLE [dbo].[MappingMenu](
	[urn] [nchar](10) NULL
) ON [PRIMARY]

GO

INSERT CashDetail VALUES
(1, '2013-11-11 00:00:00', 22.50, 'TEST'),
(2, '2013-11-11 01:22:22', 46.57, 'TEST TWO')


INSERT MappingMenu VALUES
(1),
(2),
(3),
(4),
(5),
(6),
(7)

DECLARE @sql NVARCHAR(MAX)
DECLARE @pivotsql VARCHAR(MAX)
DECLARE @columns VARCHAR(MAX)
DECLARE @selectlist VARCHAR(MAX)

SET @columns = N'';
SELECT @columns += N', c.' + QUOTENAME(urn)
FROM (SELECT c.urn FROM Cashbook.MappingMenu AS c
LEFT JOIN Cashbook.CashDetail AS m ON m.MappingMenu = c.urn
GROUP BY c.urn, m.MappingMenu) AS x;

SET @selectlist = N'';
SELECT @selectlist += N', SUM(ISNULL(' + QUOTENAME(urn) + ', 0)) AS ' +
QUOTENAME(urn) FROM (SELECT c.urn FROM Cashbook.MappingMenu AS c
LEFT JOIN Cashbook.CashDetail AS m ON m.MappingMenu = c.urn
GROUP BY c.urn, m.MappingMenu) AS x;

SET @selectlist = STUFF(@selectlist, 1, 1, '');
SET @pivotsql = N'SELECT CONVERT (VARCHAR, CreatedOn, 103) AS Date,  ' + @selectlist + '
FROM (SELECT CreatedOn, MappingMenu, Value FROM Cashbook.CashDetail AS m) AS j

PIVOT

(SUM(Value) FOR MappingMenu IN ('+ STUFF(REPLACE(@columns, ', c.[', ',['), 1, 1, '') + ')) AS c
GROUP BY c.CreatedON With ROLLUP
ORDER BY Grouping(c.CreatedON)';

EXEC (@pivotsql)

As you can see, it works perfectly. However (Grrrrr) someone has now asked if it is possible to bring in the narrative for each record.

My SQL pivot skills aren't sharp enough to work out if it's possible.

Thanks in advance for any pointers.


Viewing all articles
Browse latest Browse all 23857

Trending Articles



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