我有下表
video_id ip_address
1 192.168.1.1
1 192.168.1.1
1 192.168.1.2
2 192.168.1.2
2 192.168.1.2
2 192.168.1.2
运行以下查询将返回每个IP地址的每个视频的唯一请求数量。
SELECT video_id, COUNT(*) as num_unique_requests FROM
(SELECT video_id, ip_address FROM videos
GROUP BY video_id, ip_address) t
GROUP BY video_id
ORDER BY num_unique_requests DESC
video_id num_unique_requests
1 2
2 1
有没有办法可以将最里面的GROUP BY
语句与另一个GROUP BY
语句嵌套,这样我就可以避免创建最外层的语句GROUP BY
video_id?
还有其他方法可以更有效地编写此查询吗?
答案 0 :(得分:2)
只需使用 COUNT(DISTINCT FILEDNAME)
SELECT video_id, COUNT( DISTINCT ip_address) as num_unique_requests FROM
videos
GROUP BY video_id
ORDER BY num_unique_requests DESC
答案 1 :(得分:1)
在您的情况下,内部查询中的DISTINCT
是apt,代替GROUP BY
SELECT video_id, COUNT(*) as num_unique_requests
FROM
(SELECT DISTINCT video_id, ip_address FROM videos) t
GROUP BY video_id
ORDER BY num_unique_requests DESC