MySQL query to count non-null values in a single row

后端 未结 2 1493
孤城傲影
孤城傲影 2021-01-24 15:33

I\'m trying to put together a MYSQL query that will count the number of Non-Null (or better yet, non-zero) values in select fields in a single row and then sort from lowest to h

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-24 15:52

    try This:

    Select id, Count1, Count2, Count3, Count4
    From
        (Select 
            Sum(Case When IsNull(Score_1,0) = 0 Then 1 Else 0 End) Count1,
            Sum(Case When IsNull(Score_2,0) = 0 Then 1 Else 0 End) Count2,
            Sum(Case When IsNull(Score_3,0) = 0 Then 1 Else 0 End) Count3,
            Sum(Case When IsNull(Score_4,0) = 0 Then 1 Else 0 End) Count4
        From Table
        Group By Id) Z  -- This column (Id) better not be the PK for this table!!!
    Order By Count1 + Count2 + Count3 + Count4
    

提交回复
热议问题