时间:2021-09-14 15:05:08 | 栏目:PostgreSQL | 点击:次
我就废话不多说了,大家还是直接看代码吧~
select * from (select ROW_NUMBER () OVER (ORDER BY fat desc nulls last) AS xuhao,foodnum,foodname,fat from ek_food where isdel=0) food where foodnum = 'Ss192008'
1.排序时,字段值为null的会排在前面,导致数据不准确,解决办法 在order by后面增加 nulls last
2.给查询的结果增加序号 select ROW_NUMBER () OVER (ORDER BY fat desc nulls last) AS xuhao
补充:利用 PostgreSQL 实现对数据进行排名
user_id | name | score |
1 | john | 1000 |
2 | mike | 1200 |
3 | jelly | 1300 |
4 | brook | 1500 |
5 | nanny | 1200 |
需要知道 user_id = k 的用户对应的积分排名
SELECT user_id, name, score, RANK() OVER (ORDER BY score DESC) FROM user;
user_id | name | score | rank |
4 | brook | 1500 | 1 |
3 | jelly | 1200 | 2 |
2 | mike | 1300 | 3 |
5 | nanny | 1500 | 3 |
1 | john | 1200 | 5 |
如要获取排名 < 3 的用户:
SELECT user_id, name, score, user_rank FROM (SELECT user_id, name, score, RANK() OVER (ORDER BY score DESC) AS user_rank FROM user) AS T WHERE user_rank < 3;
-- 注意子查询在from中需要写别名
user_id | name | score | rank |
4 | brook | 1500 | 1 |
3 | jelly | 1200 | 2 |