WHERE IN中的SQL非字母顺序

时间:2014-04-29 06:02:25

标签: sql where alphabetical

假设我有这个问题:

SELECT name
FROM product
WHERE name IN ('CE367FAACDHCANPH-151556',
                  'CE367FAACEX9ANPH-153877',
                  'NI564FAACJSFANPH-162605',
                  'GE526OTACCD3ANPH-149839')

结果是:

CE367FAACDHCANPH-151556
CE367FAACEX9ANPH-153877
GE526OTACCD3ANPH-149839
NI564FAACJSFANPH-162605

按字母顺序排序

如何通过列表中的外观索引获得结果顺序?

基本上我想要这个结果:

CE367FAACDHCANPH-151556
CE367FAACEX9ANPH-153877
NI564FAACJSFANPH-162605
GE526OTACCD3ANPH-149839

2 个答案:

答案 0 :(得分:2)

您必须按列表中的这些值明确排序,例如:使用CASE表达式:

SELECT name
FROM product
WHERE name IN ('CE367FAACDHCANPH-151556',
               'CE367FAACEX9ANPH-153877',
               'NI564FAACJSFANPH-162605',
               'GE526OTACCD3ANPH-149839')
ORDER BY CASE WHEN name = 'CE367FAACDHCANPH-151556' THEN 1
              WHEN name = 'CE367FAACEX9ANPH-153877' THEN 2
              WHEN name = 'NI564FAACJSFANPH-162605' THEN 3
              WHEN name = 'GE526OTACCD3ANPH-149839' THEN 4
         END

Example on SQLFiddle

如果你想避免重复这些文字,你可以采用这个技巧:

SELECT product.name
FROM product
JOIN (
  VALUES('CE367FAACDHCANPH-151556', 1),
        ('CE367FAACEX9ANPH-153877', 2),
        ('NI564FAACJSFANPH-162605', 3),
        ('GE526OTACCD3ANPH-149839', 4)
) AS sort (name, sort)
ON product.name = sort.name
ORDER BY sort.sort

Example on SQLFiddle

答案 1 :(得分:0)

您可以使用PATINDEX。至少如果你的名字结构越来越相同。

SELECT [Name] FROM product 
ORDER BY CONVERT(INT, LEFT(Name, PATINDEX('%[^0-9]%', Name+'z')-1));

SQL Fiddle

上查看此示例