2012-04-18 12 views
6

Ho bisogno di ottenere le ultime due cifre di un numero intero. Ogni elemento inserito nelle tabelle viene considerato come un anno intero, ad esempio. YYYY e voglio solo le ultime due cifre, in modo che tutti i campi mostranoSQL ottenendo le ultime due cifre dell'intero

YEAR 
---- 
09 
00 
89 

in cui il campo initialy era

YEAR 
---- 
2009 
2000 
1989 

EDIT: ho un reclamo dicendo

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

quando provo

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

risposta

9

Postgres ha preso in prestito (o ereditato) l'operatore modulo da 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 
    ; 

Risultato:

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) 
3
select substring(CAST(2012 as CHAR(4)), 3, 2) 
1

Non so se c'è una funzione LEN su Postgres, ma se lo fa, provate questo:

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

quando ho provato ad utilizzare len() o la lunghezza() in PostgreSQL si dice che la funzione doesn' esiste – Madhusudan

0

È inoltre possibile utilizzare sotto query SQL:

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

Qui usiamo ultime due cifre dell'anno di CURRENT_TIMESTAMP

Problemi correlati