I have a single table that has thousands of rows of log statistics (number of views per page, per website) for multiple websites. For instance, in this table, multiple sites can have a separate stat for the same page name:
+----+---------+-------+------------+
| id | page | views | sitename |
+----+---------+-------+------------+
| 1 | page1 | 7 | name1 |
+----+---------+-------+------------+
| 2 | page1 | 5 | name2 |
+----+---------+-------+------------+
| 3 | page2 | 3 | name2 |
+----+---------+-------+------------+
| 4 | page1 | 7 | name3 |
+----+---------+-------+------------+
| 5 | page2 | 5 | name3 |
+----+---------+-------+------------+
| 6 | page3 | 3 | name3 |
+----+---------+-------+------------+
I am trying to formulate a query that will allow me to list each DISTINCT page name, for each DISTINCT sitename -- and display the number of views for that page per site:
+-------+----------+-------+---------+
| page | name1 | name2 | name3|
+-------+----------+-------+---------+
| page1 | 7 | 5 | 7 |
+-------+----------+-------+---------+
| page2 | NULL | 3 | 5 |
+-------+----------+-------+---------+
| page3 | NULL | NULL | 3 |
+-------+----------+-------+---------+
If a site does not have a stat for that particular page, the view value should be NULL. This leads me to think I'll need to do a JOIN/UNION some place, but I can't wrap my mind around it! How can I formulate this query when I need multiple distinct values? Thanks!
UPDATE (ANSWER WITH DYNAMIC SQL + PIVOT): PIVOT was the correct method, which both potential answers included. Gave the official credit to 2nd responder since the SUM of the values in the actual SELECT statement was the key to getting the dynamic SQL query to work properly.
http://sqlfiddle.com/#!6/7b4cb/37/0
Also, used some TSQL from here: