我试图从数据库中获取基于字母和数字格式的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 | 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 * from table
):
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 | share
-------+--------
k007 | BBCA
b454 | BBCA
a522 | BBCA
p430 | BBCA
q797 | BBCA
我希望错误发生在concat和order by之间,有人可以告诉我如何获得正确的前5个输出,例如:
nocust | share
-------+--------
a522 | BBCA
b454 | BBCA
k007 | BBCA
p430 | BBCA
q797 | BBCA
您有一个非常奇怪的ORDER BY
-它只能确保在开头带有字母的条目之前对那些以数字开头的条目进行排序-但您实际上是[[NOT根据值本身进行排序。没有特定的ORDER BY
表示:无法保证行的排序方式-如您在此处看到的。
ORDER BY
调整为: ORDER BY
CASE WHEN nocust LIKE '[a-z]%' THEN 1 ELSE 0 END,
nocust
您实际上是按[NOW
nocust
进行订购-现在,我很确定,输出将是相同的]]case when
返回0