Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Trying to sum all columns in my table and to find the top 3 of them.

columns have only a value of 1 or 0. That's why I am trying to sum the all inputs to compare them with each other.

I've stucked with order by code integrated into sum()

SELECT (ID)
FROM Student
ORDER BY SUM(C1), SUMC(C2)...SUM(C10)
lIMIT 3
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
118 views
Welcome To Ask or Share your Answers For Others

1 Answer

If I understand correctly, you can use union all to calculate the sum for each column and then order by and limit:

select c.*
from ((select 'col1', sum(col1) as s from t) union all
      (select 'col2', sum(col2) as s from t) union all
      . . . 
      (select 'col10', sum(col10) as s from t)
     ) c
order by s desc
limit 3;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...