选择具有特定顺序的特定记录而不使用常见条件

时间:2011-02-08 14:07:57

标签: sql sql-server sql-server-2008

我的目的如下:

我有一个“StudentID”列表...让我们说:4,2,3,5,7(例如存储在一个数组中), 我想创建一个select语句,返回列表中指定studentID的StudentID和StudentName, 与列表的顺序相同

所以结果应该是:

StudentID StudentName
4         Philip
2         Mary
3         Tima
5         Lara
7         Michel

我怎样才能做到这一点?

6 个答案:

答案 0 :(得分:5)

我会将这些ID数组放入临时表中,然后针对select连接该临时表。在临时表中创建标识列将保留所需的顺序。

create table #temp (
    SortID int identity,
    StudentID int
)

insert into #temp 
    (StudentID)
    select 4 union all
    select 2 union all
    select 3 union all
    select 5 union all
    select 7

select s.StudentID, s.StudentName
    from StudentTable s
        inner join #temp t
             on s.StudentID = t.StudentID
    order by t.SortID

答案 1 :(得分:3)

如果您的数据库在select语句中支持case,则以下内容将按所需顺序返回查询数据:

select 
  StudentID, 
  StudentName 
from 
  <table>
where 
  StudentID in (4,2,3,5,7)
order by 
  case studendID 
     when 4 then 1 
     when 2 then 2
     when 3 then 3
     when 5 then 4
     when 7 then 5
   end;

答案 2 :(得分:2)

使用union查询,您需要将一个order参数/值注入sql tough。

select studentId, studentName from (
    select 1 as rowOrder, studentID, studentName from <table> where studentID = 4 UNION ALL
    select 2, studentID, studentName from <table> where studentID = 2 UNION ALL
    select 3, studentID, studentName from <table> where studentID = 3 UNION ALL
    select 4, studentID, studentName from <table> where studentID = 5 UNION ALL
    select 5, studentID, studentName from <table> where studentID = 7) as x
order by rowOrder

答案 3 :(得分:0)

select studentID, studentName 
from Students 
where studentID in (4, 2, 3, 5, 7)

答案 4 :(得分:0)

这是一个版本,它将您的逗号分隔的字符串/数组拆分,然后在连接中用于学生。

declare @IDs varchar(max)
set @IDs = '4,2,3,5,7'

;with cte
as
(
  select
    left(@IDs, charindex(',', @IDs)-1) as ID,
    right(@IDs, len(@IDs)-charindex(',', @IDs)) as IDs,
    1 as Sort
  union all
  select
    left(IDs, charindex(',', @IDs)-1) as ID,
    right(IDs, len(IDs)-charindex(',', IDs)) as IDs,
    Sort + 1 as Sort
  from cte
  where charindex(',', IDs) > 1
  union all
  select
    IDs as ID,
    '' as IDs,
    Sort + 1 as Sort
  from cte
  where
    charindex(',', IDs) = 0 and
    len(IDs) > 0
)
select
  cte.ID as StudentID,
  Students.StudentName
from cte
  inner join Students
    on cte.ID = Students.StudentID  
order by cte.Sort
顺便说一下,分割字符串的方法不止一种。搜索SO将为您提供很多选择。

答案 5 :(得分:0)

试试这个:

Select * From Employees Where Employees.ID in(1,5,2,3) 
ORDER BY CHARINDEX(','+CONVERT(varchar, Employees.ID)+',', ',1,5,2,3,')