SQL计数多列

时间:2015-01-30 02:07:12

标签: mysql sql count

我有一个当前返回多个列的查询,下面是一个示例。

我要做的是计算ClientID和ServerID配对的次数。我希望获得最多服务于该客户端的ServerID。

ClientID, ServerID,  Last.Date

   1          AB       1/27/2015    
   2          DS       1/27/2015  
   1          JK       1/27/2015
   1          AB       1/24/2015
   2          PD       1/24/2015
   2          DS       1/23/2015

我想要的是什么:

ClientID ServerID Last.Date ConnectionCount

1          AB        1/27/2015  2
2          DS        1/27/2015  2

我知道我需要使用Count函数,但问题是Count(ClientID + ServerID)无效,我不确定如何基于两列计数。

提前致谢

〜杰森

4 个答案:

答案 0 :(得分:7)

您可以GROUP BY多列,以获取每个组合的计数。

SELECT ClientID, ServerID, MAX(`Last.Date`) AS `Last.Date`, COUNT(*) AS ConnectionCount
FROM YourTable
GROUP BY ClientID, ServerID

答案 1 :(得分:4)

您可以使用某些调用self-exclusion join的内容来执行表上的外连接,其中您为每组匹配记录排除除一条记录之外的所有记录。

要进行连接,您必须首先提供连接中涉及的表。对于您的情况,以下select语句将用作表:

SELECT
  ClientID
, ServerID
, count(*) as ConnectionCount
FROM Table1
GROUP BY ClientID, ServerID;

使用您的示例数据,这将产生以下结果集:

ClientID   ServerID LastDate     ConnectionCount
1          AB       1/27/2015    2
2          DS       1/27/2015    2
1          JK       1/27/2015    1
2          PD       1/24/2015    1

使用上表,我们构造了自外连接:

SELECT T1.* FROM
( SELECT
    ClientID
  , ServerID
  , max(LastDate) as LastDate
  , count(*) as ConnectionCount
  FROM Table1
  GROUP BY ClientID, ServerID
) T1
LEFT JOIN
( SELECT
    ClientID
  , ServerID
  , count(*) as ConnectionCount
  FROM Table1
  GROUP BY ClientID, ServerID
) T2
ON (...some on clause...)
WHERE ...some where clause...
;

ON子句基于您要确定每个客户端的最大服务器连接数的事实。为此,您需要将T1中的连接数与ClientId或ON (T1.ClientId = T2.ClientId)中的连接数进行比较。但这不是一个足够的ON子句只返回客户端,服务器组合与最大连接。为此,您必须从T1连接数大于所有记录的T2连接数的连接中排除记录。换句话说,没有T2行,T1连接数永远不会小于T2连接数。

根据这个逻辑,你可以提出以下条款:

ON (T1.ClientId = T2.ClientId AND T1.ConnectionCount < T2.ConnectionCount)
WHERE T2.ClientId IS NULL

将所有内容放在一起,最终的SQL查询是:

SELECT T1.* FROM
( SELECT
    ClientID
  , ServerID
  , max(LastDate) as LastDate
  , count(*) as ConnectionCount
  FROM Table1
  GROUP BY ClientID, ServerID
) T1
LEFT JOIN
( SELECT
    ClientID
  , ServerID
  , count(*) as ConnectionCount
  FROM Table1
  GROUP BY ClientID, ServerID
) T2
ON (T1.ClientId = T2.ClientId AND T1.ConnectionCount < T2.ConnectionCount)
WHERE T2.ClientId IS NULL
;

答案 2 :(得分:1)

您可以使用group by获取最大连接数,然后再在客户端再执行一次group by以获得服务最多的服务器

<强> SQL Fiddle

SELECT clientId, serverId,
max(connectionCount) as ConnectionCount, LastDate
from
(
select clientId, ServerID, 
count(*) as ConnectionCount,
max(LastDate) as LastDate
from Table1
group by clientId, ServerID
  ) t
group by clientId

答案 3 :(得分:0)

select ClientID,ServerID,Last.Date,count(ServerID) as count 
From your table
group by ServerID