SQL SQL获取整数的后两位

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10205828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 15:23:12  来源:igfitidea点击:

SQL obtaining the last two digits of integer

sqlpostgresql

提问by SNpn

I need to obtain the last two digits of an integer. Each element placed in the tables comes as a full year ie. YYYYand I only want the last two digits, so that all the fields show

我需要获取整数的最后两位数字。放置在表格中的每个元素都是一整年,即。YYYY我只想要最后两位数字,以便所有字段都显示

YEAR
----
09
00
89

where the initialy field was

初始字段在哪里

YEAR
----
2009
2000
1989

EDIT: I get a complaint saying,

编辑:我收到投诉说,

HINT: No function matches the given name and argument types. You might need to add explicit type casts.

HINT: No function matches the given name and argument types. You might need to add explicit type casts.

when i try

当我尝试

select right(cast(year as char),2) from subjects;

select right(cast(year as char),2) from subjects;

回答by wildplasser

Postgres has borrowed (or inherited) the modulus operator from C:

Postgres 从 C 中借用(或继承)了模运算符:

SET search_path='tmp';

CREATE TABLE lutser ( year integer);

INSERT INTO lutser (year)
        SELECT generate_series(1991,2012)
    ;

SELECT year
    , year / 100 as c2
    , year % 100 AS y2
    FROM lutser
    ;

Result:

结果:

CREATE TABLE
INSERT 0 22
 year | c2 | y2 
------+----+----
 1991 | 19 | 91
 1992 | 19 | 92
 1993 | 19 | 93
 1994 | 19 | 94
 1995 | 19 | 95
 1996 | 19 | 96
 1997 | 19 | 97
 1998 | 19 | 98
 1999 | 19 | 99
 2000 | 20 |  0
 2001 | 20 |  1
 2002 | 20 |  2
 2003 | 20 |  3
 2004 | 20 |  4
 2005 | 20 |  5
 2006 | 20 |  6
 2007 | 20 |  7
 2008 | 20 |  8
 2009 | 20 |  9
 2010 | 20 | 10
 2011 | 20 | 11
 2012 | 20 | 12
(22 rows)

回答by juergen d

select substring(CAST(2012 as CHAR(4)), 3, 2)

回答by Diego

I don't know if there is a LEN function on Postgres, but if it does, try this:

我不知道 Postgres 上是否有 LEN 函数,但如果有,试试这个:

select SUBSTRING(year,len(year)-1,len(year))

回答by KARISHMA JAGE

You can also use below SQL query:

您还可以使用以下 SQL 查询:

select to_char as year from to_char(current_timestamp, 'YY')

here we use last two digit of year from current_timestamp

这里我们使用 current_timestamp 中年份的最后两位数