How can I get the bottom 50% of a select query in

2020-02-06 17:08发布

In SQL server I can say:

Select top 50 percent

How can I say bottom 50 percent?

EDIT - for the sake of an interesting question, if we assume he has a table with a primary key but wants the bottom 50% ordered in ascending primary key order. What would be the most efficient way of achieving that?

6条回答
女痞
2楼-- · 2020-02-06 17:21

Your question as stated is technically meaningless because without an order by clause the order in which your data is returned is undefined (in practice most databases will return in primary key order, or if you don't have a primary key then in insertion order, but that is not guaranteed)

Assuming however you have an order by clause but just haven't included it, just would use DESC instead of ASC.

查看更多
Deceive 欺骗
3楼-- · 2020-02-06 17:24

Another option could be:

Select * From (
    Select NTILE(2) Over (Order by Quantity Desc) as HalfNumber
    From Table1) as NtileTable
where HalfNumber = 1

You can then dynamically change the division of your data as you like.

Check this out.

查看更多
我想做一个坏孩纸
4楼-- · 2020-02-06 17:29
SELECT * FROM (
        SELECT TOP 50 PERCENT *
        FROM [Table]
        ORDER BY [Field] DESC
   )
ORDER BY [Field] ASC

Does not work correct when the table contains a uneven amount of records. the one in the middle will be in both result sets.

this on the other hand works fine

SELECT * FROM <table> EXCEPT TOP 50 PERCENT...;

upvote for mingos :)

downvote for user151323 :(

查看更多
看我几分像从前
5楼-- · 2020-02-06 17:30

why not just change the sort order and keep TOP. Wouldn't that accomplish the same thing?

查看更多
Rolldiameter
6楼-- · 2020-02-06 17:30

I dunno whether this would work:

SELECT * FROM <table> EXCEPT TOP 50 PERCENT...;

And I'm pretty sure something like this would be OK too:

SELECT * FROM <table> WHERE (ID NOT IN (SELECT TOP 50 PERCENT ...));

Just check the syntax, as I'm only beginning to learn SQL and can't form correct queries without modifying the a million times first ;)

查看更多
ゆ 、 Hurt°
7楼-- · 2020-02-06 17:33
    SELECT * FROM
    (
        SELECT TOP 50 PERCENT *

        FROM [Table]

        ORDER BY [Field] DESC
   )
   ORDER BY [Field] ASC
查看更多
登录 后发表回答