Nik*_*war 3 sql sqlite group-by sql-order-by
我有以下场景,我想订购表格,并按具有最高到最低金额的组排列
name score
----------------
abc 10
pqr 9
abc 7
pqr 3
abc 10
xyz 7
pqr 7
xyz 3
xyz 2
Run Code Online (Sandbox Code Playgroud)
现在,如果我们观察,
总(abc)= 10 + 7 + 10 = 27
总(pqr)= 9 + 3 + 7 = 19
总(xyz)= 7 + 3 + 2 = 12
如何SQL
按最高总和的组对上表进行排序,它应该显示单个条目?
Expected output:
----------------
name score
----------------
abc 10
abc 10
abc 7
pqr 9
pqr 7
pqr 3
xyz 7
xyz 3
xyz 2
Run Code Online (Sandbox Code Playgroud)
SQLite没有分析/窗口函数,因此您需要自己计算出不同的数据.
SELECT
yourTable.*
FROM
yourTable
INNER JOIN
(
SELECT name, SUM(score) AS score FROM yourTable GROUP BY name
)
AS totalScores
ON totalScores.name = yourTable.name
ORDER BY
totalScores.score DESC,
yourTable.name,
yourTable.score DESC
Run Code Online (Sandbox Code Playgroud)
在此查询中,有一个子查询.子查询计算每个名称的totalScore.
然后,您可以将该总分放在ORDER BY子句中.注意,我没有在我的结果中选择总分,你可以,但没有必要.
另外,我把名字放在ORDER BY中.这样,如果存在多个名称共享相同总分的并列,则首先按字母顺序显示第一个名称.