获取的SQL分组与任何帖子无关

时间:2018-01-15 16:51:19

标签: sql

我有一张这样的表:

Hour    Operation   IP
10  GET     192.168.1.3
10  POST    192.168.1.3
10  GET     192.168.1.4
10  GET     192.168.1.8
12  POST    192.168.1.7
12  GET     192.168.1.7
12  GET     192.168.1.9

我需要知道每个小时有多少不同的GET操作没有关联的POST操作(没有购买的访问)

答案是:

Hour GETs
10 2
12 1

但我不清楚如何做到这一点。

2 个答案:

答案 0 :(得分:0)

嗯。嗯。 。 。我想你想要:

select hour, sum(case when posts > gets then gets - posts else 0 end)
from (select ip, hour,
             sum(case when operation = 'GET' then 1 else 0 end) as gets,
             sum(case when operation = 'POST' then 1 else 0 end) as posts
      from t
      group by ip, hour
     ) ih
group by hour;

这是相当棘手的,因为大概给定的IP可能会在同一时间内有多个获取和放置。

答案 1 :(得分:0)

这应该有效:

 SELECT HOUR, COUNT(IP) FROM 
 (
   SELECT HOUR, IP FROM mytable a WHERE Operation = 'GET' and NOT EXISTS
    ( SELECT 1 FROM mytable b WHERE Operation = 'POST' AND a.IP = b.IP AND 
      a.HOUR = b.HOUR
    )
) as a
GROUP BY HOUR

甚至更短:

SELECT HOUR, COUNT(IP) 
FROM mytable a 
WHERE Operation = 'GET' 
AND NOT EXISTS
(
  SELECT 1 FROM mytable b 
  WHERE Operation = 'POST' 
  AND a.IP = b.IP 
  AND a.HOUR = b.HOUR
)
GROUP BY HOUR