[MySQL SELECT count with ORDER BY

问题描述 投票:1回答:1
SELECT * FROM `rank` WHERE entry_id = '90901' ORDER BY position ASC
229298400   90901   33
232322400   90901   33
227487600   90901   37
229903200   90901   38
228092400   90901   41
228693600   90901   43
225673200   90901   45
230508000   90901   47

SELECT position FROM `rank` WHERE entry_id = '90901' ORDER BY position ASC LIMIT 1 
33

SELECT position, count(*) as Weeks FROM `rank` WHERE entry_id = '90901' ORDER BY position ASC LIMIT 1 
45  8

请说明为什么返回'45'(倒数第二个?),以及如何计算所有条目并获得最高的条目。

mysql
1个回答
0
投票

如果要查询entry_id,则查询max(position)

DROP TABLE IF EXISTS T;
CREATE TABLE t(id int,entry_id int,position int);
insert into t values
(229298400 ,  90901  , 33),
(232322400 ,  90901  , 33),
(227487600 ,  90901  , 37),
(229903200 ,  90901  , 38),
(228092400 ,  90901  , 41),
(228693600 ,  90901  , 43),
(225673200 ,  90901  , 45),
(230508000 ,  90901  , 47);

select max(position) , count(*)
from t
where entry_id = 90901;

+---------------+----------+
| max(position) | count(*) |
+---------------+----------+
|            47 |        8 |
+---------------+----------+
1 row in set (0.001 sec)

如果您希望每个entry_id都相同,则>]

select entry_id, max(position) , count(*)
from t
group by entry_id

+----------+---------------+----------+
| entry_id | max(position) | count(*) |
+----------+---------------+----------+
|    90901 |            47 |        8 |
+----------+---------------+----------+
1 row in set (0.001 sec)
© www.soinside.com 2019 - 2024. All rights reserved.