我有以下代码:
select publ_id
, title
, t1.page_count
, ( select count(page_count)
from a_bkinfo.books as t2
where t2.page_count < t1.page_count
and t2.publ_id = t1.publ_id) as Rank
from a_bkinfo.books as t1|
where page_count is not null
and page_count <> 0
and publ_id is not null
order by publ_id, rank
我得到以下结果:
+---------+-------------------------------------- . -+------------+------+ | publ_id | title . | page_count | Rank | +---------+-------------------------------------- . -+------------+------+ | 9000 | Practical Standards for VB.NET . | 250 | 1 | | 9000 | Programming SQL Server with VB.NET . | 300 | 2 | | 9000 | T_SQL Programming (Inside series) . | 390 | 3 | | 9000 | T_SQL Querying (Inside series) . | 391 | 4 | | 9000 | .Net Development for Microsoft Office . | 500 | 5 | | 9000 | Applied .NET Framework Programming VB . | 608 | 6 | | 9000 | Programming Visual Basic 2005: The La . | 980 | 7 | | 9020 | Bird Sense . | 265 | 0 | | 9020 | The Unfeathered Bird . | 304 | 1 | | 9021 | Outstanding Mosses and Liverworts of . | 9 | 0 | | 9021 | Winter Weed Finder: A Guide to Dry Pl . | 64 | 1 | | 9021 | The Great Agnostic: Robert Ingersoll . | 256 | 2 | | 9021 | Bark: A Field Guide to Trees of the N . | 280 | 3 | | 9021 | Hornworts and Liverworts in your Gard . | 501 | 4 | | 9021 | Lichens of North America . | 828 | 5 | | 9021 | Outstanding Bryophytes . | 956 | 6 | | 9022 | The Leafcutter Ants: Civilization by . | 160 | 0 | | 9022 | The Social Conquest of Earth . | 352 | 1 | | 9022 | The Ants . | 732 | 2 | ... +---------+-------------------------------------- . -+------------+------+
Here is full downloadable csv file
I want the first ranking starts with 1 but some start with 1 and some start with 0. If I add change
where t2.page_count < t1.page_count
to
where t2.page_count <= t1.page_count
then some publ_id start with 2 and some start with 1.
How do I fix this by having all rank start with 1?
I used this the following code to get all form the source table which is a_bkinfo.books
select * from a_bkinfo.books
和输出
这里是完整的downloadable csv file
最佳答案
要获得一致的结果,子查询的 WHERE
子句中的条件必须与外部选择中的条件相同。试试这个方法
SELECT publ_id
,title
,page_count
,(
SELECT 1 + COUNT(page_count) -- start with 1
FROM books
WHERE page_count < t.page_count
AND publ_id = t.publ_id
AND page_count IS NOT NULL -- use the same conditions as in the outer select
AND page_count > 0 -- use the same conditions as in the outer select
AND publ_id IS NOT NULL -- use the same conditions as in the outer select
) rank
FROM books t
WHERE page_count IS NOT NULL
AND page_count > 0
AND publ_id IS NOT NULL
ORDER BY publ_id, rank
这是 SQLFiddle 演示
关于MySQL - 从最小到最大的嵌套排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20449580/