以字符串格式对星期日期进行排序

时间:2017-01-02 18:08:56

标签: sql sql-server

我在包含两列weekamount的表格中有数据,如下所示

Week                      Amount
--------------------------------
1w - 1m - 2015             1000
4w - 8m - 2015             1000
2w - 2m - 2015             1000
4w - 6m - 2015             1000
3w - 3m - 2015             1000
3w - 10m - 2015            1000
1w - 10m - 2015            1000
3w - 12m - 2015            1000
1w - 6m - 2016             1000
2w - 6m - 2016             1000
3w - 6m - 2016             1000
4w - 6m - 2016             1000
3w - 8m - 2016             1000
2w - 9m - 2016             1000

如何按周(作为日期)对此表进行排序?

我想要的输出是:

     Week                    Amount
    --------------------------------
    1w - 1m - 2015             1000
    2w - 2m - 2015             1000
    3w - 3m - 2015             1000
    4w - 6m - 2015             1000
    4w - 8m - 2015             1000
    1w - 10m - 2015            1000
    3w - 10m - 2015            1000
    3w - 12m - 2015            1000
    1w - 6m - 2016             1000
    2w - 6m - 2016             1000
    3w - 6m - 2016             1000
    4w - 6m - 2016             1000
    3w - 8m - 2016             1000
    2w - 9m - 2016             1000

2 个答案:

答案 0 :(得分:5)

Select *
 From  YourTable
 Order by right([Week],4)
         ,cast(substring([Week],charIndex('m',[Week])-2,2) as int)
         ,left([Week],1)

返回

week            Amount
1w - 1m - 2015  1000
2w - 2m - 2015  1000
3w - 3m - 2015  1000
4w - 6m - 2015  1000
4w - 8m - 2015  1000
1w - 10m - 2015 1000
3w - 10m - 2015 1000
3w - 12m - 2015 1000
1w - 6m - 2016  1000
2w - 6m - 2016  1000
3w - 6m - 2016  1000
4w - 6m - 2016  1000
3w - 8m - 2016  1000
2w - 9m - 2016  1000

答案 1 :(得分:1)

对已接受的答案进行评分,如果表格结构可以更改(添加一些列),则可以使用持久计算列以更加友好的方式存储数据。这会花费一些存储空间和一些额外的数据插入计算工作,但它将使未来的选择更快,因为不再需要字符串解析。此外,每列都有适当的类型,因此很难获得无效数据。

<强>设定:

create table WeekData
(
    WeekStr VARCHAR(16) NOT NULL,
    Amount INT,
    YearVal AS CAST (Right(WeekStr,4) AS SMALLINT) PERSISTED,
    MonthVal AS cast(substring(WeekStr,charIndex('m', WeekStr)-2,2) as SMALLINT),
    WeekVal AS CAST(left(WeekStr,1) AS TINYINT)
)

insert into WeekData (WeekStr, Amount) 
VALUES ('1w - 1m - 2015', 1000),
('4w - 8m - 2015', 1000),
('2w - 2m - 2015', 1000),
('4w - 6m - 2015', 1000),
('3w - 3m - 2015', 1000),
('3w - 10m - 2015', 1000),
('1w - 10m - 2015', 1000),
('3w - 12m - 2015', 1000),
('1w - 6m - 2016', 1000),
('2w - 6m - 2016', 1000),
('3w - 6m - 2016', 1000),
('4w - 6m - 2016', 1000),
('3w - 8m - 2016', 1000),
('2w - 9m - 2016', 1000)
GO

选择

select WeekStr, Amount 
from WeekData
order by YearVal, MonthVal, WeekVal