简体   繁体   English

如何计算SQL中的多个字段

[英]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. 我有一个存储IP的数据库。 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. 我想浏览这两个字段,并为它们提取所有不同的IP,然后找出每个IP作为客户端和服务器出现了多少次。

http://forums.devx.com/showthread.php?t=19168 <-- this was kind of similar but not quite. http://forums.devx.com/showthread.php?t=19168 <-这有点相似,但不太完全。

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. 这没有用,因为我意识到我只查看client_ip字段中的IP。

So, how can I can I count how may time each IP shows up in the server and the client field? 那么,如何计算每个IP在服务器和客户端字段中显示的时间? 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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM