通过消除多个列和行中的NULL获得不同的行

时间:2019-05-15 15:54:09

标签: sql-server

我正在处理查询,但只停留在其中一部分。此时的表如下所示:

id|classid|start|end|CurrentScore|lastYearScore|CurrentTotal|lastYearTotal  
1 |32     |1.23 |2.5|NULL        |NULL         |9.0         |NULL  
1 |32     |1.23 |2.5|7           |NULL         |NULL        |NULL  
1 |32     |1.23 |2.5|NULL        |15           |NULL        |NULL  
1 |32     |1.23 |2.5|NULL        |NULL         |NULL        |20  
...

我正在寻找的结果是这样的:

id|classid|start|end|CurrentScore|lastYearScore|CurrentTotal|lastYearTotal  
1 |32     |1.23 |2.5|7           |15           |9.0         |20  

有没有办法做到这一点?

1 个答案:

答案 0 :(得分:3)

GROUP BYMAX()配合使用将有助于获得预期的结果。

查询将是:

SELECT id, classid, [start], [end],
       MAX(CurrentScore) AS CurrentScore, 
       MAX(lastYearScore) AS lastYearScore,
       MAX(CurrentTotal) AS CurrentTotal,
       MAX(lastYearTotal) AS lastYearTotal  
FROM TableName
GROUP BY id, classid, [start], [end]