How to find the top three column totals using SQL

故事扮演 提交于 2019-12-13 08:37:52

问题


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

回答1:


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;



回答2:


try -

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


来源:https://stackoverflow.com/questions/56326146/how-to-find-the-top-three-column-totals-using-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!