0

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

ありがとう、

ジェームズ

4

2 に答える 2

2

を使用して値を集計しますMAX

SELECT ID, 
       MAX(score1) score1,
       MAX(score2) score2,
       MAX(score3) score3
FROM tableName
GROUP BY ID
于 2012-10-17T09:24:36.560 に答える
1

これは、同じ 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) を作成するジョンの回答を好むかもしれません。

于 2012-10-17T09:30:42.623 に答える