获取最高和最低价值的用户

问题描述 投票:0回答:3

我正在使用SQLite并尝试从所有评论中获得具有最低和最高总计得分的用户 - 即获得具有最低和最高综合得分的用户。总结得分的表看起来有点像这样:

CREATE TABLE comments (
     id PRIMARY KEY,
     username STRING,
     body TEXT,
     score INT
);

我期待这样的结果,显示组合得分最高和最低的用户:

userMin|-194
userMax|543

我能够显示得分最低的用户,或者单独得分最高的用户,但无法同时显示。这是我如何获得MAX和MIN:

SELECT username,  
   MAX(combinedSum) 
FROM (SELECT author, SUM(score) AS combinedSum FROM comments GROUP BY username) 
   comments;

=> userMax|543

要么

SELECT username,  
   MIN(combinedSum) 
FROM (SELECT author, SUM(score) AS combinedSum FROM comments GROUP BY username) 
   comments;

=> userMin|-194

请问有人可以帮我怎么做?

sql sqlite
3个回答
1
投票

试试这个查询:

 SELECT username,  
       MAX(combinedSum) 
    FROM (SELECT author, SUM(score) AS combinedSum FROM comments GROUP BY username) 
       comments;
    UNION
    SELECT username,  
       MIN(combinedSum) 
    FROM (SELECT author, SUM(score) AS combinedSum FROM comments GROUP BY username) 
       comments;

1
投票

我会用CTE:

with t as (
      select username, sum(score) as sum_score
      from comments
      group by username
     )
select t.*
from t join
     (select min(sum_score) as min_sum_score, max(sum_score) as max_sum_score
      from t
     ) tt
     on t.sum_score in (tt.min_sum_score, tt.max_sum_score);

0
投票
select * 
from (SELECT a, sum(b) 'b' from t group by a) tt1 
where b in(select max(t1.b) from(SELECT a, sum(b) 'b' from t group by a) t1
    union select min(t2.b) from(SELECT a, sum(b) 'b' from t group by a) t2)

看起来HAVING毕竟不能做这项工作

© www.soinside.com 2019 - 2024. All rights reserved.