开发者

SQL Server 2008 order by conditional

I have a query:

DECLARE @MyTemp TABLE
(
  MyField VARCHAR(20)
)

INSERT INTO @MyTemp VALUES ( 'BBA' )
INSERT INTO @MyTemp VALUES ( 'ABA' )
INSERT INTO @MyTemp VALUES ( 'AAA' )
INSERT INTO @MyTemp VALUES ( 'BAA' )


SELECT * FROM @MyTemp
O开发者_开发知识库RDER BY MyField

What I want is to order alphabetically, EXCEPT for anything that starts with BA, which I want last.

I have tried this:

SELECT * FROM @MyTemp
ORDER BY MyField, CASE MyField LIKE 'BA%' WHEN 1 THEN 1 ELSE 0 END

Which doesn't work. I have tried IIF, CONTAINS all without success.

How can I do this?


Change the ORDER BY to

ORDER BY CASE WHEN MyField LIKE 'BA%' THEN 1 ELSE 0 END, MyField
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜