如何按相关表上一列的总和来排序SELECT查询?

时间:2018-09-02 21:33:42

标签: sql sqlite

我有一个职位表和一个评级表。一个帖子可以有多个评分,并且评分可以是任何正整数。

在SQL中,如何表达SELECT查询,该查询将返回按其评分总和排序的帖子?

作为参考,示例模式:

CREATE TABLE Posts (
    id INT PRIMARY_KEY
);

CREATE TABLE Ratings (
    id INT PRIMARY_KEY,
    post_id INT REFERENCES Posts(id),
    rating INT 
);

此外,我只需要发帖,但这主要是无关紧要的。

3 个答案:

答案 0 :(得分:0)

    .headers on

create table posts ( 'posts' char(20)) ;
create table ratings ( posts char(20), 'rating' number) ;  
insert into post values ( 'post1') ;
insert into post values ( 'post2') ;
insert into post values ( 'post3') ;
insert into ratings values ( 'post1', 1 ) ;
insert into ratings values ( 'post1', 3 ) ;
insert into ratings values ( 'post1', 6 ) ;
insert into ratings values ( 'post2', 2 ) ;
insert into ratings values ( 'post2', 8 ) ;
insert into ratings values ( 'post3', 1 ) ;
insert into ratings values ( 'post3', 1 ) ;

select a.post , sum(b.rating) from post a
join ratings b on a.post = b.post
group by a.post
order by sum(b.rating) ;

输出:

post|sum(b.rating)
post3|2
post1|10
post2|10

答案 1 :(得分:0)

假设有2个表,一个主键和一个外键用法以及一个帖子名称可能被重用的事实,我将给出以下内容:

   select p.post_name, sum(r.rating) as post_rating
     from posts p, ratings r
    where p.post = r.post
 group by r.post, p.post_name
 order by post_rating desc, post_name asc

答案 2 :(得分:0)

您不清楚是否要发布具有 no 评分的帖子。如果是这样,请使用left join

select p.post, sum(r.rating)
from post p left join
     ratings r
     on p.post = r.post
group by p.post
order by sum(r.rating) desc;

(我假设您首先要最高的金额;因此desc。)

如果您只想要带有评分的帖子,则不需要join

select r.post, sum(r.rating)
from ratings r
group by r.post
order by sum(r.rating) desc;