我一直试图找出如何转换返回2位数的select结果,然后将其转换为年份,这样就可以获取该年的max()值。
我的桌子:
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等等..。
我的选择状态如下所示:
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这将返回:
year
---------
98
10
97但当我使用max时,它会返回每个字母的最高数字,但在得到最高的数字之前,我需要将这2个数字转换为年份格式,这样它就可以理解17实际上是最高的,因为我们是在2017年。
发布于 2017-05-16 17:07:26
正如Sean在他的评论中所说的,在尝试以一种有意义的方式使用它之前,您必须将您的substring()转换成一个有意义的值。
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 descrextester演示:http://rextester.com/ZRV37957
返回:
+-----+------+
| Ltr | Year |
+-----+------+
| A | 2012 |
| B | 2010 |
| C | 2003 |
+-----+------+https://stackoverflow.com/questions/44007100
复制相似问题