Last active
October 4, 2018 17:14
-
-
Save sqldeployhelmet/1bad1a36014819b4a7b32e1f2c047a89 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* A pivoted list of contacts */ | |
WITH contactsCTE AS (SELECT a.acctNo | |
, c.name | |
, c.email | |
, ROW_NUMBER() OVER (PARTITION BY a.acctNo ORDER BY c.ContactID) AS ConNumber | |
FROM contacts c JOIN accounts a ON a.acctNo = c.acctNo) | |
SELECT acctNo | |
, MIN(name1) AS Name1 | |
, MIN(email1) AS Email1 | |
, MIN(name2) AS Name2 | |
, MIN(email2) AS Email2 | |
FROM (SELECT cte.acctNo | |
, 'Name' + CAST(cte.ConNumber AS VARCHAR) AS NameNumber --<=== This creates a valid column name | |
, cte.name --<=== The actual values that will be attached to the named column | |
, 'Email' + CAST(cte.ConNumber AS VARCHAR) AS EmailNumber | |
, cte.email | |
FROM contactsCTE cte) AS pvt | |
PIVOT (MIN(name) | |
FOR NameNumber IN ([Name1], [Name2])) AS NamePvt --<== include as many col + # values in this set as want to ultimately return in the row | |
PIVOT (MIN(email) | |
FOR EmailNumber IN ([Email1], [Email2])) AS EmailPvt | |
GROUP BY acctNo; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment