如何计算sql中的多个字段

时间:2010-10-12 19:38:19

标签: sql

嘿,我发现很多人都在问类似我的问题,但不完全一样。

我有一个存储IP的数据库。有一个服务器字段和一个客户端字段。我想查看这两个字段并为它们提取所有不同的IP,然后找出每个IP作为客户端和服务器的出现次数。

http://forums.devx.com/showthread.php?t=19168< - 这有点相似但不完全。

这就是我现在所拥有的:

use mydb   
select y.client_ip as "IP",  
(select count(*)  
from t_Events x  
where start_time BETWEEN '10/7/2010 08:00:00 AM' AND '10/7/2010 04:00:00 PM' AND     x.client_ip = y.client_ip) as "Count of client IP",  
(select count(*)  
from t_Events x  
where start_time BETWEEN '10/7/2010 08:00:00 AM' AND '10/7/2010 04:00:00 PM' AND   x.client_ip = y.server_ip) as "Count of Server IP"  
from t_Events y  
Group By y.client_ip, y.server_ip  

这不起作用,因为我意识到我只是在查看client_ip字段中的IP。

那么,我怎样才能算出每个IP在服务器和客户端字段中显示的时间? 我是否需要先制作临时表?

1 个答案:

答案 0 :(得分:4)

尝试这样的事情:

select IP, sum(ClientCount) as ClientCount, sum(ServerCount) as ServerCount
from (
    select client_ip as IP, count(*) as ClientCount, null
    from t_Events
    where start_time BETWEEN '10/7/2010 08:00:00 AM' AND '10/7/2010 04:00:00 PM'
    group by client_ip 
    union all
    select server_ip as IP, null, count(*) as ServerCount
    from t_Events
    where start_time BETWEEN '10/7/2010 08:00:00 AM' AND '10/7/2010 04:00:00 PM'
    group by server_ip 
) a
group by IP