samedi 18 juin 2016

How can I pivot a 2-column key/value table to a matrix of bits showing which combinations exist?

I have a table with two columns (a key and a value), that I want to pivot into a matrix of all the combinations of keys and values. I need to do this in SQL Server 2008 R2.

I'm starting with a data like the table below, which just associates two values. This example associates people to the software they have installed. Let's call this table PersonApps.

Name      | App
------------------
Joe       | Excel
Joe       | Word
Megan     | Word
Megan     | Skype
Bjorn     | SSMS
Bjorn     | Excel

I want to turn that into this:

Name   | Excel   | Word   | Skype  | SSMS
------------------------------------------
Joe    | 1       | 1      | 0      | 0
Megan  | 0       | 1      | 1      | 0
Bjorn  | 1       | 0      | 0      | 1

I know this involves the PIVOT operator, and probably some dynamic SQL since I will not know before hand how many different values may be in the Apps column. However, all the examples I can find for PIVOT are more complicated than what I need and use standard aggregate operators like COUNT and SUM, but I just need to check the existence of a combination.

The best script I can come up with is

 SELECT Name, Excel, Word, Skype, SSMS
 FROM PersonApps
 PIVOT (
     COUNT(Name) FOR App IN (Excel, Word, Skype SSMS)
 )

I know the call to COUNT is wrong. How do I make that a bit for testing the existence of a combination? Is there anything else I need to fix?


EDIT:

This code seems to be working. Is there a better way though?

SELECT *
FROM @PersonApps
PIVOT (
    COUNT(App) FOR App IN (Excel, Word, SSMS, Skype) 
) as Pivoted

Aucun commentaire:

Enregistrer un commentaire