sql - 如何通过相关表上的列的总和对 SELECT 查询进行排序?
问题描述
我有一个帖子表和一个评级表。一篇文章可以有多个评分,评分可以是任何正整数。
在 SQL 中,我如何表达一个 SELECT 查询,该查询将返回按评分总和排序的帖子?
作为参考,示例架构:
CREATE TABLE Posts (
id INT PRIMARY_KEY
);
CREATE TABLE Ratings (
id INT PRIMARY_KEY,
post_id INT REFERENCES Posts(id),
rating INT
);
另外,我只需要帖子,但这主要是无关紧要的。
解决方案
.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
推荐阅读
- python - 访问函数内所有参数名称和所有参数值的列表
- php - 如何使用 guzzle promise 获取所有分页数据
- c# - 获取多个datagridew c#的数据
- php - 如何计算所有行中等于相同id的列?
- ruby - Windows 上的 Jekyll 不编译 SASS
- javascript - 修改脚本以折叠提交表单上的 div
- c# - 尝试获取 StudentId=1 的“等级”时出错
- python - 使用 numpy.histogram 的输出如何绘制简单的曲线图?
- linux - Thymeleaf sec:authorize 和 sec:authentication 属性,对生产不生效,但在 IDE 上工作正常
- php - Cloudways 的弹性电子邮件插件与自定义 PHP