我有一个包含用户互联网历史记录的表格。表格的结构包含 User_ID ,页面访问以及页面的访问日期。例如:
+==========================================+
|User_ID | Page_Accessed | Date_Accessed |
+==========================================+
|Johh.Doe | Google | 1/1/2015 |
|Johh.Doe | Google | 1/1/2015 |
|Suzy.Lue | Google | 7/11/2015 |
|Suzy.Lue | Wikipedia | 4/23/2015 |
|Babe Ruth| StackOverflow | 9/1/2015 |
+==========================================+
我目前正在尝试使用以下的SQL查询:
RANK() OVER (PARTITION BY [Page Accessed] ORDER BY Count(DateAcc))
然后我使用各种网站的PIVOT()。但是,在从PIVOT()和GROUP BY [Rank]中选择记录WHERE (Num = 1)
之后,我最终得到的结果类似于:
+=================================================+
|Rank | Google | Wikipedia | StackOverflow |
+=================================================+
| 1 | John Doe| NULL | NULL |
| 1 | NULL | Suzy Lue | NULL |
| 1 | NULL | NULL | Babe Ruth |
+=================================================+
相反,我需要将输出重新格式化为:
+=================================================+
|Rank | Google | Wikipedia | StackOverflow |
+=================================================+
| 1 | John Doe| Suzy Lue | Babe Ruth |
+=================================================+
我当前的查询:
SELECT Rank, Google, Wikipedia, StackOverflow
FROM(
SELECT TOP (100) PERCENT User_ID, Page_Accessed, COUNT(Date_Accessed) AS Views,
RANK() OVER (PARTITION BY Page_Accessed ORDER BY Count(Date_Accessed) DESC) AS Rank
FROM Record_Table
GROUP BY dbo.location_key.subSite, dbo.user_info_list_parse.Name
ORDER BY Views DESC) AS tb
PIVOT (
max(tb.User_ID) FOR
Page_Accessed IN ( Google, Wikipedia, StackOverflow)
) pvt
WHERE (Num = 1)
是否有任何创造性的解决方案可以获得此结果?
答案 0 :(得分:1)
我认为您已经找到了解决方案但是对于您的信息以及其他人阅读此内容 - 让我在此查询中删除噪音。无需ORDER BY,无需应用TOP(100)PERCENT,视图列是多余的。我会简化这个查询,如下所示:
{{1}}