SQL将许多行组合成一行



我无法弄清楚如何在sql中进行以下选择:

表:

id score1 score2 score3
0  null   null   3
0  1      null   3
1  null   2      null

选择:

id score1 score2 score3
0  1      null   3
1  null   2      null

谢谢,

james

使用 MAX

汇总值
SELECT ID, 
       MAX(score1) score1,
       MAX(score2) score2,
       MAX(score3) score3
FROM tableName
GROUP BY ID

这是基于选择比其他任何行的分数要多的行。如果可以的话,请保留"最佳"数据。

select id, score1, score2, score3
from (
    select *,
       rn=row_number() over (partition by id
                             order by
                                case when score1 is not null then 1 else 0 end
                                +
                                case when score2 is not null then 1 else 0 end
                                +
                                case when score3 is not null then 1 else 0 end desc)
    from tbl
) x
where rn=1

,例如

id score1 score2 score3
0  null   4      null
0  1      null   3         <<< keep
1  null   2      null

当然,您可能更喜欢约翰的答案,这将使ID = 0的行(0,1,4,3)。

最新更新