我想基于两个不同查询的总和对表现最佳的广告进行排序。我该怎么办?
比方说,我正在跟踪比赛的球员统计数据,并具有以下模型:
class Player(db.Model):
id = db.Column(db.String(1024), primary_key=True)
name = db.Column(db.String(80))
dob = db.Column(TIMESTAMP, nullable=True)
start_ts = db.Column(TIMESTAMP, server_default=text('CURRENT_TIMESTAMP'), nullable=False)
end_ts = db.Column(TIMESTAMP, nullable=True)
school_id = db.Column(db.String(1024), db.ForeignKey('school.id'), nullable=False)
class School(db.Model):
id = db.Column(db.String(1024), primary_key=True)
name = db.Column(db.String(80))
address = db.Column(db.String(80))
state = db.Column(db.String(2))
class GameStats(db.Model):
id = db.Column(db.String(1024), primary_key=True)
date = db.Column(TIMESTAMP, server_default=text('CURRENT_TIMESTAMP'), nullable=False)
player_id = db.Column(db.String(1024), db.ForeignKey('school.id'), nullable=False)
scored = db.Column(Numeric(0, 0), nullable=False)
我想生成这样的报告格式:
player.id | player.name | total_score (scored from day 1 + day2) | school.name | school.state
前10名球员的总得分。最简单的方法是什么?我可以使用python / sqlalchemy或sql。
答案 0 :(得分:1)
通过SQL:
SELECT
player.id,
player.name,
SUM(gamestats.scored) AS total_score,
school.name,
school.state
FROM
player
INNER JOIN school
ON player.school_id = school.id
INNER JOIN gamestats
ON player.id = gamestats.player_id
WHERE
gamestats.date >= <whatever day 1 is>
AND gamestats.date <= <whatever day 2 is>
GROUP BY
player.id,
player.name,
school.name,
school.state
ORDER BY
total_score DESC
LIMIT 10;
根据所使用的SQL类型,可以更改限制10个结果的方法。 LIMIT 10与netezza一起使用,SELECT TOP 10与Microsoft sql等一起使用,等等。