是否可以将GROUP BY语句嵌套在彼此内?

时间:2012-11-30 06:44:34

标签: mysql

我有下表

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?

还有其他方法可以更有效地编写此查询吗?

2 个答案:

答案 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