客户ID如下:
AMT-2
AMT-100
AMT-1
AMT-50
AMT-10
所以我想订购客户ID:
AMT-1
AMT-2
AMT-10
AMT-50
AMT-100
怎么办?请帮帮我。
答案 0 :(得分:2)
这可能会对你有帮助,
SELECT *
FROM Customer
ORDER BY Cast(SUBSTRING(CustomerID, 5, Len(CustomerID)) As Numeric(5,0));
<强> fiddleExample 强>
答案 1 :(得分:1)
如果您知道前缀的长度始终相同,则可以执行以下操作:
order by len(customerid), customerid
答案 2 :(得分:0)
使用AMT -
函数从字符串中删除RIGHT
部分,并将其余部分转换为整数,并按结果对结果进行排序。
<强>查询强>
SELECT *
FROM customerId
ORDER BY CONVERT(INT,RIGHT(id,LEN(id)-5));
<强> Fiddle demo 强>
答案 3 :(得分:0)
假设所有客户ID都具有相同的前缀(例如AMT-), 后缀是数字, 您可以使用SubString来获取数值, 并相应地进行排序。
CREATE TABLE [dbo].[Customers](
[CustomerID] [varchar](50) NULL
) ON [PRIMARY]
INSERT INTO [dbo].[Customers]
([CustomerID])
VALUES
('AMT-2'),('AMT-100'),('AMT-1'),('AMT-50'),('AMT-10')
declare @prefix varchar(4) = 'AMT-'
SELECT *--,cast(SUBSTRING(CustomerID,len(@prefix) + 1,len(CustomerID) - len(@prefix) + 1) as int)
FROM Customers
order by cast(SUBSTRING(CustomerID,len(@prefix) + 1,len(CustomerID) - len(@prefix) + 1) as int)
答案 4 :(得分:0)
试试这个order by
order by convert(int,(substring(col,charindex('-',col)+1,len(col))))
答案 5 :(得分:0)
如果模式相同,也可以尝试
select customer_id from table
order by substring(customer_id,5,len(customer_id))*1
答案 6 :(得分:0)
您可以CAST
将列XML
输入customerid
并从中提取数字,然后根据SELECT * INTO #TEMP
FROM
(
SELECT 'AMT-1' customerid
UNION ALL
SELECT 'AMT-2'
UNION ALL
SELECT 'AMT-10'
UNION ALL
SELECT 'AMT-50'
UNION ALL
SELECT 'AMT-100'
)TAB
列中的数字进行排序。
示例数据
;WITH CTE AS
(
SELECT
-- Actual customerid column
ISNULL(PARSENAME(Split.a.value('.', 'VARCHAR(100)'),2),Split.a.value('.', 'VARCHAR(100)')) 'customerid' ,
-- Extract numbers from string and keep a column that sorts the numbers numerically
ROW_NUMBER() OVER(ORDER BY CAST(PARSENAME(REPLACE(Split.a.value('.', 'VARCHAR(100)'),'-','.'),1) AS NUMERIC(20,0))) 'RNO'
FROM
(
-- Converts to XML format
SELECT CAST ('<M>' + customerid + '</M>' AS XML) AS Data
FROM #TEMP
) AS A
CROSS APPLY Data.nodes ('/M') AS Split(a)
)
SELECT customerid
FROM CTE
ORDER BY customerid,RNO
<强> QUERY 强>
{{1}}
答案 7 :(得分:-1)
DECLARE @t TABLE (CUSTOMER_ID nvarchar(100))
INSERT INTO @t VALUES ('AMT-2'),('AMT-100'),('AMT-1'),('AMT-50'),('AMT-10'),('AMT-98')
SELECT * from @t
ORDER BY RIGHT(REPLICATE(N' ', 50) + CUSTOMER_ID, 50)
我认为这会对你有所帮助
如果有帮助,请将此标记为答案或投票