Solved

SQL Server Pivot Query

Posted on 2016-07-21
5
31 Views
Last Modified: 2016-07-21
I have an email table with 3 columns
CampaignID
emailaddress
typeresponse

the typeresponse has 5 possible types (open, bounce, deferred, click, unsubscribe)

I need a select that groups by CampaignID and emailaddress
And then place a 1 or 0 in the 5 pivoted columns if that record exists

As in
CampaignID   emailaddress    open     bounce     deferred     click    unsubscribe
12345              test@live.com     1               0                 0                1              0
0
Comment
Question by:lrbrister
  • 2
  • 2
5 Comments
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
Comment Utility
select campaignid
,email
,max(case when typeresponse ='open' tben 1 else 0 end ) [open]
.... same for the other typeresponsed...
from yourtable
group by campaignid
, email
0
 
LVL 11

Expert Comment

by:Nakul Vachhrajani
Comment Utility
You can use the PIVOT operator:

DECLARE @campaignTable TABLE (CampaignID INT            NOT NULL,
                              EmailAddress VARCHAR(255) NOT NULL,
                              TypeResponse VARCHAR(25)  NOT NULL
                             );

INSERT INTO @campaignTable (CampaignID, EmailAddress, TypeResponse)
VALUES (123, 'openresponse@123.com',         'Open'),
       (123, 'bouncedresponse@123.com',      'Open'),
       (123, 'bouncedresponse@123.com',      'Bounce'),
       (123, 'clickresponse@123.com',        'Open'),
       (123, 'clickresponse@123.com',        'Click'),
       (234, 'donotdisturbresponse@123.com', 'Open'),
       (234, 'donotdisturbresponse@123.com', 'Unsubcribe'),
       (345, 'bouncedresponse@123.com',      'Open'),
       (345, 'bouncedresponse@123.com',      'Bounce'),
       (345, 'deferredresponse@123.com',     'Deferred'),
       (345, 'clickresponse@123.com',        'Open'),
       (345, 'clickresponse@123.com',        'Click');


SELECT PivotedTable.CampaignID,
       PivotedTable.EmailAddress,
       PivotedTable.[Open],
       PivotedTable.[Bounce],
       PivotedTable.[Deferred],
       PivotedTable.[Click],
       PivotedTable.[Unsubscribe]
FROM (SELECT ct.CampaignID,
             ct.EmailAddress,
             ct.TypeResponse
      FROM @campaignTable AS ct
     ) AS SourceTable
PIVOT (COUNT(SourceTable.TypeResponse) FOR TypeResponse IN ([Open], 
                                                            [Bounce], 
                                                            [Deferred], 
                                                            [Click], 
                                                            [Unsubscribe]
                                                           )
      ) AS PivotedTable
ORDER BY PivotedTable.CampaignID,
         PivotedTable.EmailAddress

Open in new window


Results of PIVOT operator
1
 

Author Comment

by:lrbrister
Comment Utility
Perfect... as always thanks.
Quick follow-up
This may be run on 50k records at a time.
Should that be a concern if the indexes are "optimized?"
0
 
LVL 142

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 500 total points
Comment Utility
50k records is not big.
and unless a clustered index on either campaignid or email a index is not needed or helpful
0
 

Author Closing Comment

by:lrbrister
Comment Utility
angelll,
As always... thanks for your help.

You cave me one of my first solutions back in 2004 I believe.
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Suggested Solutions

Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now