April 29, 2015 at 11:48 am
Hello, the subject pretty much says it all. I have the following result set but I want to stack or transpose the 3 fields into a single column. I may add more fields later, but right now I want to know what's the best and simplest way.
Current result set:
TotalAllCustomersOnFile | TotalConsumersWithValidEmail | TotalConsumersWithValidEmailAndOptedIn
2,500 1,750 1,500
Desired result set:
Audience | Totals
----------------------------------------------------
TotalAllCustomersOnFile | 2,500
TotalConsumersWithValidEmail | 1,750
TotalConsumersWithValidEmailAndOptedIn | 1,500
April 29, 2015 at 12:05 pm
latingntlman (4/29/2015)
Hello, the subject pretty much says it all. I have the following result set but I want to stack or transpose the 3 fields into a single column. I may add more fields later, but right now I want to know what's the best and simplest way.Current result set:
TotalAllCustomersOnFile | TotalConsumersWithValidEmail | TotalConsumersWithValidEmailAndOptedIn
2,500 1,750 1,500
Desired result set:
Audience | Totals
----------------------------------------------------
TotalAllCustomersOnFile | 2,500
TotalConsumersWithValidEmail | 1,750
TotalConsumersWithValidEmailAndOptedIn | 1,500
Quick suggestion
😎
USE tempdb;
GO
SET NOCOUNT ON;
;WITH X(TotalAllCustomersOnFile,TotalConsumersWithValidEmail,TotalConsumersWithValidEmailAndOptedIn) AS
(SELECT * FROM (VALUES ('2,500', '1,750', '1,500')) AS X(TotalAllCustomersOnFile,TotalConsumersWithValidEmail,TotalConsumersWithValidEmailAndOptedIn)
)
SELECT
XY.Audience
,XY.Totals
FROM X
CROSS APPLY
(
SELECT 'TotalAllCustomersOnFile' AS Audience, TotalAllCustomersOnFile AS Totals UNION ALL
SELECT 'TotalConsumersWithValidEmail' AS Audience,TotalConsumersWithValidEmail AS Totals UNION ALL
SELECT 'TotalConsumersWithValidEmailAndOptedIn' AS Audience,TotalConsumersWithValidEmailAndOptedIn AS Totals
) AS XY;
Results
Audience Totals
-------------------------------------- ------
TotalAllCustomersOnFile 2,500
TotalConsumersWithValidEmail 1,750
TotalConsumersWithValidEmailAndOptedIn 1,500
April 29, 2015 at 12:31 pm
And just to give a second option.
WITH X(TotalAllCustomersOnFile,TotalConsumersWithValidEmail,TotalConsumersWithValidEmailAndOptedIn) AS
(SELECT * FROM (VALUES ('2,500', '1,750', '1,500')) AS X(TotalAllCustomersOnFile,TotalConsumersWithValidEmail,TotalConsumersWithValidEmailAndOptedIn)
)
SELECT
XY.Audience
,XY.Totals
FROM X
UNPIVOT
( Totals FOR Audience IN
( TotalAllCustomersOnFile
,TotalConsumersWithValidEmail
,TotalConsumersWithValidEmailAndOptedIn )
) AS XY;
References:
APPLY method: http://www.sqlservercentral.com/articles/CROSS+APPLY+VALUES+UNPIVOT/91234/
UNPIVOT method: https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx
April 29, 2015 at 3:54 pm
Thank you both. I'll work to implement one of these suggestions.
Viewing 4 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply