如何基于两列对行进行排序,您首先按column1
进行排序,但是如果行具有相同的值(并列),则按column2
对行进行排序?
id | likes | date
---+-------+-----
0 0 203
1 8 100
2 4 24
3 1 340
4 4 262
5 4 82
因此对于上面的示例表,首先基于likes
进行排序,然后对于具有4
的3行,基于date DESC
进行排序?
注意:date
仅具有任意的unix时间戳记值
编辑: 这是我正在使用的实际查询:
SELECT * FROM (SELECT posts.id, posts.topic_id, topics.name,
posts.author_id, users.username, users.profile_pic, posts.date_posted,
posts.body, posts.coordinates, (SELECT COUNT(*) FROM post_likes WHERE
post_likes.post_id = posts.id) AS num_likes,
ROW_NUMBER () OVER (ORDER BY (SELECT COUNT(*) FROM post_likes WHERE
post_likes.post_id = posts.id) DESC, posts.date_posted DESC) AS RowNum
FROM posts INNER JOIN users ON posts.author_id = users.id INNER JOIN
topics ON posts.topic_id = topics.id WHERE author_id = 'foo') AS
RowConstrainedResult WHERE RowNum > 0 AND RowNum <= 20 ORDER BY RowNum
答案 0 :(得分:0)
您将命令其为
<
select
from table
>
order by likes desc
, date desc
答案 1 :(得分:0)
我认为这是您所需要的:
Select * from table
ORDER BY likes, date DESC;
这将产生如下输出:
id likes date
0 0 203
3 1 240
4 4 262
5 4 82
2 4 24
1 8 100
检查DEMO here。