【发布时间】:2020-02-01 11:26:04
【问题描述】:
我之前的问题已经回答了Select top using SQL Server returns different output than select *
我想从基于字母和编号格式的数据库中获取select top n 数据。输出必须先按字母排序,然后按数字排序。
当我尝试获取所有数据 (select *) 时,我得到了正确的输出:
select nocust, share
from TB_STOCK
where share = ’BBCA’
and concat(share, nocust) < ‘ZZZZZZZZ’
order by
case when nocust like ‘[a-z]%’ then 0 else 1 end, nocust
nocust | share
-------+--------
a522 | BBCA
b454 | BBCA
k007 | BBCA
p430 | BBCA
q797 | BBCA
s441 | BBCA
s892 | BBCA
u648 | BBCA
v107 | BBCA
4211 | BBCA
6469 | BBCA
6751 | BBCA
当我尝试select top n(例如:前 5 名)时,我也得到了正确的数据:
select top 5 nocust, share
from TB_STOCK
where share = ’BBCA’
and concat(share, nocust) < ‘ZZZZZZZZ’
order by
case when nocust like ‘[a-z]%’ then 0 else 1 end, nocust
nocust | share
-------+--------
a522 | BBCA
b454 | BBCA
k007 | BBCA
p430 | BBCA
q797 | BBCA
问题是当我尝试根据最后一次攻击获得下一个前 5 名并分享之前的前 5 名数据时
(concat(share, nocust) < 'ZZZZq797'))
它返回错误的预期数据:
select top 5 nocust, share
from TB_STOCK
where share = ’BBCA’
and concat(share, nocust) < ‘ZZZZq797’
order by
case when nocust like ‘[a-z]%’ then 0 else 1 end, nocust
nocust | share
-------+--------
a522 | BBCA
b454 | BBCA
k007 | BBCA
p430 | BBCA
q797 | BBCA
它应该返回:
nocust | share
-------+--------
s441 | BBCA
s892 | BBCA
u648 | BBCA
v107 | BBCA
4211 | BBCA
我预计错误在 concat 和 order by 之间,有人可以告诉我如何获得正确的前 5 名。
【问题讨论】:
-
顺便说一句,我注意到您尚未接受任何问题的答案。请阅读this 并考虑接受您现有问题的答案。
标签: sql-server sql-server-2008 select sql-order-by