如何将一行与SQL

时间:2018-05-24 11:53:45

标签: sql sql-server

我有一个由团队成员组成的数据集。

我想计算成员2的平均值。

但是,有一些条件可以满足计算,

例如,id 1让Anna和Sam一起工作,我想只计算成员2这是Sam

为此,我想总结具有

的ID的分数
  • Sam和他一起工作,就像id:2 member1:Sam member2:Sam
  • 一样
  • Sam与其他成员合作但不与Anna(member1)合作,如id:3 member1:Sam member2:Nihalid:4 member1:Nihal member2:Sam

然后除以不同的#ID

输入

+----+---------+---------+-------+
| ID | member1 | member2 | score |
+----+---------+---------+-------+
|  1 | Anna    | Sam     |    10 |
|  2 | Sam     | Sam     |    30 |
|  3 | Sam     | Nihal   |    40 |
|  4 | Nihal   | Sam     |    50 |
|  5 | Sam     | Anna    |    20 |
|  6 | Anna    | Anna    |    60 |
|  7 | Nihal   | May     |    70 |
|  8 | May     | May     |    80 |
+----+---------+---------+-------+

输出

+----+---------+---------+-------+-----+
| ID | member1 | member2 | score | AVG |
+----+---------+---------+-------+-----+
|  1 | Anna    | Sam     |    10 |  40 |-->AVG= 30+40+50/3
|  2 | Sam     | Sam     |    30 |  30 |-->AVG= score
|  3 | Sam     | Nihal   |    40 |  70 |-->AVG= 70/1
|  4 | Nihal   | Sam     |    50 |  20 |-->AVG= 30+10+20/3
|  5 | Sam     | Anna    |    20 |  60 |-->AVG= 60/1
|  6 | Anna    | Anna    |    60 |  60 |-->AVG= score
|  7 | Nihal   | May     |    70 |  80 |-->AVG= 80/1
|  8 | May     | May     |    80 |  80 |-->AVG= score
+----+---------+---------+-------+-----+

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

select t1.*,q.avg_score
from yourtable t1
cross apply
(
    select avg(score) as avg_score
    from yourtable t2
    where 
        t1.member2 in (t2.member1,t2.member2)
        and t1.member1 not in  (t2.member1,t2.member2)
)q