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

时间:2017-12-23 10:37:46

标签: sql sqlite

我正在使用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

有人可以帮我解决这个问题吗?

3 个答案:

答案 0 :(得分: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 :(得分: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);

答案 2 :(得分: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毕竟无法完成这项工作