我想在select语句中使用Order by子句来对以下数据中的nvarchar字段进行排序。
1/2013
1/2014
2/2013
3/2013
5/2010
25/2013
115/2013
26/2014
我希望按以下结果排序:
5/2010
1/2013
2/2013
3/2013
25/2013
115/2013
1/2014
26/2014
我使用以下查询,但它无法正常工作。
SELECT DebitNote
FROM DebitNote
ORDER BY CONVERT(
INT,
SUBSTRING(debitnote, CHARINDEX('/', debitnote) + 1, 4),
CONVERT(INT, SUBSTRING(debitNOte, 0, CHARINDEX('/', debitNOte)))
)
答案 0 :(得分:0)
试试这个 -
DECLARE @DebitNote TABLE (DebitNote VARCHAR(50))
INSERT INTO @DebitNote (DebitNote)
VALUES
('1/2013'), ('1/2014'), ('2/2013'),
('3/2013'), ('5/2010'),
('25/2013'), ('26/2014')
SELECT DebitNote
FROM @DebitNote
ORDER BY CAST('1/' + DebitNote AS DATETIME)
输出 -
DebitNote
-----------------
5/2010
1/2013
2/2013
3/2013
25/2013
1/2014
26/2014
<强>更新强>
DECLARE @DebitNote TABLE (DebitNote VARCHAR(50))
INSERT INTO @DebitNote (DebitNote)
VALUES
('1/2013'), ('1/2014'),
('2/2013'), ('3/2013'),
('5/2010'), ('25/2013'),
('26/2014'), ('116/2013'),
('115/2013'), ('315/2014')
SELECT DebitNote
FROM @DebitNote
ORDER BY
SUBSTRING(DebitNote, CHARINDEX('/', DebitNote) + 1, 4)
, CONVERT(INT, SUBSTRING(DebitNote, 0, CHARINDEX('/', DebitNote)))
答案 1 :(得分:0)
根据经验,我以一种我将在12个月内不费吹灰之力地理解的方式编写代码。同样,这意味着我希望其他开发人员也能轻松理解这一点。
所以在这种情况下,我不会在ORDER BY
子句中隐藏这个神秘的逻辑。通过将值作为SELECT
子句的一部分,我会使事情更加透明。
DECLARE @t table (
DebitNote nvarchar(10)
);
INSERT INTO @t (DebitNote)
VALUES ('1/2013')
, ('1/2014')
, ('2/2013')
, ('3/2013')
, ('5/2010')
, ('25/2013')
, ('115/2013')
, ('26/2014');
SELECT DebitNote
FROM (
SELECT DebitNote
, CharIndex('/', DebitNote) As position_of_slash
, Cast(SubString(DebitNote, 0, CharIndex('/', DebitNote)) As int) As first_part
, SubString(DebitNote, CharIndex('/', DebitNote) + 1, 10) As last_part -- Note that the last parameter of the SubString() function here
-- equals the length of the field in question
FROM @t
) As x
ORDER
BY last_part
, first_part;
如果首选
,最后一个查询可以进入CTE; WITH component_parts AS (
SELECT DebitNote
, CharIndex('/', DebitNote) As position_of_slash
, Cast(SubString(DebitNote, 0, CharIndex('/', DebitNote)) As int) As first_part
, SubString(DebitNote, CharIndex('/', DebitNote) + 1, 10) As last_part -- Note that the last parameter of the SubString() function here
-- equals the length of the field in question
FROM @t
)
SELECT DebitNote
FROM component_parts
ORDER
BY last_part
, first_part;