代码之家  ›  专栏  ›  技术社区  ›  Sorskoot

按值列表排序查询结果

  •  6
  • Sorskoot  · 技术社区  · 15 年前

    我正在处理一个将值列表作为参数传递的SQL查询,比如

    select * 
    from ProductGroups
    where GroupID in (24,12,7,14,65)
    

    此列表由数据库中使用的关系构成,必须按此顺序保存。

    我想按此列表订购结果。我只需要第一个结果,但在本例中可能是groupid为7的结果。

    我不能这样问

    order by (24,12,7,14,65).indexOf(GroupId)
    

    有人知道怎么做吗?

    其他信息:
    构建一个连接并在MSSQL查询编辑器中运行它,但是…

    由于向MSSQL发送查询的软件的限制,我必须将它作为一个参数传递给一些内部查询生成器,因此是“24、12、7、14、65”。我不知道前面这个列表中会有多少个数字,可能是2,也可能是20。

    4 回复  |  直到 11 年前
        1
  •  7
  •   Unsliced    11 年前

    使用带有标识列的表变量或临时表,输入值并连接到该变量或临时表,例如。

    declare @rank table (
        ordering int identity(1,1)
        , number int    
        )
    
    insert into @rank values (24)
    insert into @rank values (12)
    insert into @rank values (7)
    insert into @rank values (14)
    insert into @rank values (65)
    
    select  pg.*
    from    ProductGroups pg
    left outer join 
        @rank r
    on  pg.GroupId = r.number 
    order by 
        r.ordering
    
        2
  •  10
  •   Andomar    15 年前

    您还可以通过以下方式订购:

    select * 
    from ProductGroups
    where GroupID in (24,12,7,14,65)
    order by case GroupId 
        when 7 then 1 -- First in ordering
        when 14 then 2 -- Second
        else 3
    end
    
        3
  •  4
  •   Sorskoot    15 年前

    我想我可能找到了一个可能的解决办法(但很难看):

    select * 
    from ProductGroups
    where GroupID in (24,12,7,14,65)
    order by charindex(
                 ','+cast(GroupID as varchar)+',' ,
                 ','+'24,12,7,14,65'+',')
    

    这将按行在列表中出现的位置对行进行排序。我也可以按自己的需要传递字符串。

        4
  •  2
  •   Alex Weinstein    15 年前

    使用一个临时表进行联接,在该表中,您希望按行筛选值。向其中添加一列,该列的顺序与第二列的顺序相同,然后按该列排序。