简体   繁体   中英

How to find the top three column totals using SQL

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

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;

try -

    SELECT TOP 3 (ID)
    FROM Student
    GROUP BY (ID)
    ORDER BY SUM(C1), SUMC(C2)...SUM(C10) DESC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM