2013-02-08 113 views
1
J12M1 
J12M14 
J12M15 
J12M18 
J12M2 
J12M21 
J12M22 
J12M23 
J12M24 
J12M25 
J12M26 
J12M27 
J12M28 
J12M29 
J12M35 
J12M36 
J12M39 

,但我需要的是排序依據數字Colunm

J12M1 
J12M2 
J12M3 

我能在我的查詢做

select productnumber from vt_fe_product order by productnumber 
+0

哪裏'J12M3'在第二個列表從何而來?這不在你的第一個列表中。 –

回答

2

您可以用零前面加上:

SELECT 
    productnumber 
FROM 
    vt_fe_product 
ORDER BY 
    Right('0000000000' + productnumber, 10) 

(來源: https://stackoverflow.com/a/3326371/284240

Demo

結果:

PRODUCTNUMBER 
J12M1 
J12M2 
J12M14 
J12M15 
J12M18 
J12M21 
J12M22 
J12M23 
J12M24 
J12M25 
J12M26 
J12M27 
J12M28 
J12M29 
J12M35 
J12M36 
J12M39 
+0

+1我以前從未見過那招。 – Taryn

+0

@bluefeet:我也是!瞭解它[這裏](http://stackoverflow.com/a/3326371/284240)。 –

0

如果productnumber格式良好定義(即它將始終是'J12M'後跟一個數字),那麼您可以刪除'固定'部分併爲您的排序投下數字部分。沿線的東西:

ORDER BY CONVERT(int, REPLACE(productnumber, 'J12M', '')) 
1

也許你需要嘗試使用額外的LEN功能?

SELECT ProductName 
FROM 
(
SELECT 
'J12M1' AS ProductName 
UNION ALL 
SELECT 
'J12M14' AS ProductName 
....................... 
UNION ALL 
SELECT 
'J12M24' AS ProductName 
UNION ALL 
SELECT 
'J12M25' AS ProductName 
UNION ALL 
SELECT 
'J12M35' AS ProductName 
UNION ALL 
SELECT 
'J12M36' AS ProductName 
UNION ALL 
SELECT 
'J12M39' AS ProductName 
) AS Products 
ORDER BY LEN(ProductName), ProductName 
0

您可以訂購這種方式: -

select product_number from vtfe_product order by CONVERT(int, substring(product_number, 5, len(product_number)));

0

已經看到了其他的答案。決定採取不同的路線。有點比較冗長,但是這個解決方案的好處是你最終會對實際的數字進行排序,並且首先對'J'數字進行排序。

SELECT 
    -- Get the first numeric component 
    CAST (
     SUBSTRING(
      productnumber, 
      CHARINDEX('J', productnumber, 1) + 1, 
      CHARINDEX('M', productnumber, 1) - CHARINDEX('J',productnumber, 1) - 1) 
     AS INT 
    ) AS FirstSort, 
    -- Get the second numeric component 
    CAST (
     SUBSTRING(
      productnumber, CHARINDEX('M', productnumber, 1) + 1, LEN(productnumber)) 
     AS INT 
    ) AS SecondSort, 
    productnumber 
FROM 
    productnumbers 
ORDER BY 
    FirstSort, 
    SecondSort 

DEMO

http://sqlfiddle.com/#!6/fd371/2