计算个人在当前团队之前与其他团队成员之间的先前关系

时间:2017-11-17 21:49:43

标签: sql sql-server-2008 select count

我想计算每个成员在成立现有团队之前与其他团队成员之间的先前关系数。

我有下表



TeamId	UserId	Date
1	    100	  2/1/2017 
1	    101	  2/1/2017
1	    102	  2/1/2017 
2	    100	  2//1/2016
2	    105   2//1/2016
3   	    100	  2//1/2015
3	    101	  2//1/2015
3   	    102	  2//1/2015
3   	    105	  2//1/2015
3	    106	  2//1/2015
4	    101   1/3/2015
4	    102	  1/3/2015
4	    105   1/3/2015
4   	    106	  1/3/2015




我想获得下表



TeamId	number of previous collaborations
1       	4
2	        1
3       	6
4	        0




例如对于团队1: 用户100已经在团队3中与用户101进行了一次协作,并且在团队3中与用户102进行了一次协作,因此= 1 + 1 = 2 用户101与用户102合作两次(一次在团队3中,一次在团队4中)= 1 + 1 = 2

所以此团队以前的合作次数为4次。

我不知道如何编写代码。任何帮助表示赞赏



SELECT [TeamId],
COUNT( SELECT [Date] FROM [submissions] s1
       WHERE s.[UserId] = [submissions].[UserId]
       AND [Date]< [submissions].[Date]
       ORDER BY [DateSubmitted] DESC) as Num_Collaborations
     )
FROM [submissions]
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

您可以通过自我加入获得所有用户协作:

select s.userid, s2.userid as userid2, s.date,
       row_number() over (order by (select null)) as c_id
from submissions s join
     submissions s2
     on s2.teamid = s.teamid;

让我们将其用作子查询来回答您的问题。我们的想法是将协作与提交内容相匹配 - 约束两个用户在以后的日期在同一个团队中。然后,您可以聚合:

with c as (
      select s.userid, s2.userid as userid2, s.date,
             row_number() over (order by (select null)) as c_id
      from submissions s join
           submissions s2
           on s2.teamid = s.teamid
     )
select s1.teamid, count(distinct c_id) as num_previous_collaborations
from c c join
     submissions s1
     on s1.userid = c.userid and
        s1.date > c.date join  -- they are later on a team
     submissions s2
     on s2.userid = c.userid2 and
        s2.teamid = s1.teamid 
group by s1.teami;

答案 1 :(得分:1)

这是一个具有挑战性的问题。您必须在查询中包含相同的表4次:

select t1.TeamId, t1.UserId, t2.TeamId as OtherTeam, t3.UserId as Collaborator
from @table t1, @table t2, @table t3, @table t4
where t1.UserId = t2.UserId and
      t2.TheDate < t1.TheDate and
      t3.TeamId = t2.TeamId and
      t4.TeamId = t1.TeamId and
      t4.UserId = t3.UserId and
      t4.UserId < t1.UserId

http://rextester.com/LHZS40204

(然后你可以分组并计算得到最终结果)