开发者

how to count multiple fields in sql

Hey I've found a lot of people asking questions similar to mine but not exactly the same.

I have a database that stores IPs. There开发者_运维技巧 is a server field and a client field. I want to look through both these fields and pull out all the distinct IPs for them and then find out how many occurrences there are of each IP as a client and as a server.

http://forums.devx.com/showthread.php?t=19168 <-- this was kind of similar but not quite.

This is what I have right now:

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  

this didn't work because I realize I'm only looking at IPs that are in the client_ip field.

So, how can I can I count how may time each IP shows up in the server and the client field? Do I need to make a temp table first?


Try something like this:

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 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜