简体   繁体   中英

Convert datetime from substring T-SQL

I have been trying to figure out how to convert a select result that returns 2 digits and then I want to convert it into year so then I can grab the max() value of that year.

My table:

ins_order
------------------------
RSN  |  ordered
---------------
1    |  A04-01
2    |  A12-02
3    |  A98-01
4    |  B00-10
2    |  B10-02
3    |  C97-01
4    |  C03-10

and so on...

My select state looks like this:

select 
    max(substring(orderid, patindex('%[0-9]-%', orderid) - 1, 2)) as year
from 
    ins.insorders
where 
    orderid is not null
group by 
    substring(orderid, 0, patindex('%[0-9]%', orderid))
order by 
    year

This will return:

year
---------
98           
10
97

but when I use max it returns the highest number for each letter, but before getting the highest number I need to convert this 2 numbers into year format so it can understand that 17 is actually the highest because we are in 2017.

As Sean Lange said in his comment, you are going to have to convert your substring() to a meaningful value before trying to use it in a meaningful way.

select 
    Ltr = substring(orderid, 0, patindex('%[0-9]%', orderid))
  , Year = max(case when convert(int,substring(orderid, patindex('%[0-9]-%', orderid) - 1, 2)) < 50
  then convert(int,'20'+substring(orderid, patindex('%[0-9]-%', orderid) - 1, 2))
  else convert(int,'19'+substring(orderid, patindex('%[0-9]-%', orderid) - 1, 2))
  end)
from ins_orders
group by substring(orderid, 0, patindex('%[0-9]%', orderid))
order by year desc

rextester demo: http://rextester.com/ZRV37957

returns:

+-----+------+
| Ltr | Year |
+-----+------+
| A   | 2012 |
| B   | 2010 |
| C   | 2003 |
+-----+------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM