Exclude top and bottom n rows in SQL

别说谁变了你拦得住时间么 提交于 2020-01-01 07:19:06

问题


I'm trying to query a database but excluding the first and last rows from the table. Here's a sample table:

id | val
--------
 1    1
 2    9
 3    3
 4    1
 5    2
 6    6
 7    4

In the above example, I'd first like to order it by val and then exclude the first and last rows for the query.

id | val
--------
 4    1
 5    2
 3    3
 7    4
 6    6

This is the resulting set I would like. Note row 1 and 2 were excluded as they had the lowest and highest val respectively.

I've considered LIMIT, TOP, and a couple of other things but can't get my desired result. If there's a method to do it (even better with first/last % rather than first/last n), I can't figure it out.


回答1:


You can try this mate:

SELECT * FROM numbers
WHERE id NOT IN (
    SELECT id FROM numbers
    WHERE val IN (
        SELECT MAX(val) FROM numbers
    ) OR val IN (
        SELECT MIN(val) FROM numbers
    )
);



回答2:


You can try this:

Select * 
from table
where 
val!=(select val from table order by val asc LIMIT 1) 
and 
val!=(select val from table order by val desc LIMIT 1)
order by val asc;

You can also use UNION and avoid the 2 val!=(query)




回答3:


What if you use UNION and exclude the val you don't want. Something like below

select * from your_table
where val not in (
select top 1 val from your_table order by val

union

select top 1 val from your_table order by val desc)



回答4:


;WITH cte (id, val, rnum, qty) AS (
    SELECT  id
    ,       val
    ,       ROW_NUMBER() OVER(ORDER BY val, id)
    ,       COUNT(*) OVER ()
    FROM    t
)
SELECT  id
,       val
FROM    cte
WHERE   rnum BETWEEN 2 AND qty - 1


来源:https://stackoverflow.com/questions/28750940/exclude-top-and-bottom-n-rows-in-sql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!