如何在另外两列中获得具有最大相等值的组?

时间:2014-05-07 07:50:39

标签: sql sql-server-2008

     Session                          initial final 
5a2572b8-c7bc-4e53-8731-266764fa4285    10     10
5a2572b8-c7bc-4e53-8731-266764fa4286    10     10
5a2572b8-c7bc-4e53-8731-266764fa4287    10     10
5a2572b8-c7bc-4e53-8731-266764fa4288    10     10
5a2572b8-c7bc-4e53-8731-266764fa4288    13     14
5a2572b8-c7bc-4e53-8731-266764fa4288    10     10
5a2572b8-c7bc-4e53-8731-266764fa4289    10     10
5a2572b8-c7bc-4e53-8731-266764fa4289    11     10
5a2572b8-c7bc-4e53-8731-266764fa4210    14     14
5a2572b8-c7bc-4e53-8731-266764fa4210    11     10 

我在SQL中有上面的表(测试),我需要计算具有最大匹配数的会话,其中initail = final,反之亦然

2 个答案:

答案 0 :(得分:0)

您可以将common-table-expression与OVER clause

一起使用
WITH CTE AS
(
  SELECT Session, initial, final,
     Sum = SUM(CASE WHEN initial=final THEN 1 END) Over (Partition By Session)
  FROM dbo.Test
)
SELECT TOP 1 Session FROM CTE ORDER BY SUM DESC

Demo

我认为“反之亦然”意味着相反的顺序。然后你只需要使用ORDER BY SUM ASC。如果您想要通过不相等的初始最终值(如上所述)进行排序,则可以使用此查询:

WITH CTE AS(
  SELECT 
     Session, initial, final,
     SumSame    = SUM(CASE WHEN initial=final  THEN 1 END) Over (Partition By Session),
     SumNotSame = SUM(CASE WHEN initial<>final THEN 1 END) Over (Partition By Session)
  FROM dbo.Test
)
SELECT TOP 1 Session
FROM CTE
ORDER BY SumSame DESC

现在您可以将其更改为ORDER BY SumNotSame DESC以获得最大不平等会话。

Demo

答案 1 :(得分:0)

要获得最大匹配数的会话很容易。只需选择所有匹配项,逐个会话并获取最高记录。不匹配也是如此。他们在这里结合起来:

select 
  match.session as match_session,
  match.cnt as match_count,
  mismatch.session as mismatch_session,
  mismatch.cnt as mismatch_count
from
(
  select top(1) session, count(*) as cnt
  from sessions
  where initial = final
  group by session
  order by session desc
) match
cross join
(
  select top(1) session, count(*) as cnt
  from sessions
  where initial != final
  group by session
  order by session desc
) mismatch;