如何按照条件in里面的进行排序

strugglesun 2011-03-28 04:17:52
例:表A中的数据为,如下:
ID Name
1 Li
2 Zhang
3 Chen
4 Wang
5 Zhao
6 Gao
7 Xu

SQL: select * from A where ID in (3,2,5,4,7,6)

查询的结果如下:
ID Name
2 Zhang
3 Chen
4 Wang
5 Zhao
6 Gao
7 Xu
我想要的结果是:
ID Name
3 Chen
2 Zhang
5 Zhao
4 Wang
7 Xu
6 Gao
请问这样怎样按照条件in里面的进行排序?


...全文
117 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
danssion 2011-08-24
  • 打赏
  • 举报
回复
[Quote=引用 11 楼 bluesmiler 的回复:]

SELECT * FROM t WHERE ID in (3,2,5,4,7,6)
ORDER BY CHARINDEX(cast (id as varchar),'3,2,5,4,7,6')
[/Quote]

给力的
danssion 2011-08-24
  • 打赏
  • 举报
回复
给力的解答哦 哦
bluesmiler 2011-03-28
  • 打赏
  • 举报
回复
SELECT * FROM t WHERE ID in (3,2,5,4,7,6)
ORDER BY CHARINDEX(cast (id as varchar),'3,2,5,4,7,6')


--小F-- 2011-03-28
  • 打赏
  • 举报
回复
select
*
from
t
where
id in (3,2,5,4,7,6)
order by
charindex(ltrim(id),'3,2,5,4,7,6')
ztxneter 2011-03-28
  • 打赏
  • 举报
回复
SELECT * FROM t WHERE ID in (3,2,5,4,7,6)
ORDER BY CHARINDEX(LTRIM(id),'3,2,5,4,7,6')
dearbinge 2011-03-28
  • 打赏
  • 举报
回复

DECLARE @TB TABLE(ID INT)
INSERT INTO @TB
SELECT 3
UNION ALL
SELECT 2
UNION ALL
SELECT 5
UNION ALL
SELECT 4
UNION ALL
SELECT 7
UNION ALL
SELECT 6
SELECT T.ID,A.NAME FROM @TB T
LEFT JOIN A
ON T.ID=A.ID
strugglesun 2011-03-28
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 eaglexie 的回复:]
后加ORDER BY ID ASC看看
[/Quote]
后面默认的就是ORDER BY ID ASC这个。
eaglexie 2011-03-28
  • 打赏
  • 举报
回复
后加ORDER BY ID ASC看看
strugglesun 2011-03-28
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 lf19820717 的回复:]
in里面的是集合,不带顺序的
[/Quote]
但是查询出来的结果,默认的就按照ID进行了升序排序,怎样取消这个默认排序?
Rotel-刘志东 2011-03-28
  • 打赏
  • 举报
回复
select id,name from A where ID =3
union all
select id,name from A where ID =2
union all
select id,name from A where ID =5
union all
select id,name from A where ID =4
union all
select id,name from A where ID =7
union all
select id,name from A where ID =6
javatemptation 2011-03-28
  • 打赏
  • 举报
回复
in里面的是集合,不带顺序的
strugglesun 2011-03-28
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 xuam 的回复:]
SQL code

select * from A where ID =3
union all
select * from A where ID =2
union all
select * from A where ID =5
union all
select * from A where ID =4
union all
select * from A where ID =7
……
[/Quote]
这位兄台可能还不是很明白我的意思,
我的意思是,就在这条语句上修改:select * from A where id in (3,2,5,4,7,6),得到想要的结果。
xuam 2011-03-28
  • 打赏
  • 举报
回复

select * from A where ID =3
union all
select * from A where ID =2
union all
select * from A where ID =5
union all
select * from A where ID =4
union all
select * from A where ID =7
union all
select * from A where ID =6



22,210

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧