找到前两列的总和以及它们有多少积分?

时间:2019-05-28 08:38:53

标签: mysql sql sql-order-by

尝试使用求和函数查找前2列。

列可以是 0 1 整数值。

表可以看作:

ID  C_ONE C_TWO C_THREE
1     1     1     0
2     0     1     1
3     1     1     0
4     0     0     0
5     1     1     0

C_TWO 列具有 4 点,而 C_ONE 列具有 3 点,分别是前2列及其值。

我坚持使用此代码。

SELECT COUNT(ID)
FROM MY_TABLE
ORDER BY SUM(C_ONE), SUM(C_TWO), SUM(C_THREE)
LIMIT 2

1 个答案:

答案 0 :(得分:1)

好吧,您可以取消透视和聚合:

select c.col,
       (case when c.col = 'col1' then t.col1
             when c.col = 'col2' then t.col2
             when c.col = 'col3' then t.col3
        end) as cnt
from (select sum(col1) as col1, sum(col2) as col2, sum(col3) as col3
      from t
     ) t cross join
     (select 'col1' as col union all
      select 'col2' as col union all
      select 'col3' as col
     ) c
order by cnt desc
limit 2;