Pregunta

I have a list of Rainfall data

SELECT * FROM Rainfall

COUNTRY         YEAR  AMT
--------------  ----  ---
Austria         2000  1.1
Belgium         2000  1.2
France          2000  1.3
Ireland         2000  1.4

France          2001  1.5
Ireland         2001  1.6

Austria         2002  1.7
Belgium         2002  1.8
France          2002  1.9

Germany         2003  2.0
Italy           2003  2.1

How would I select this showing all countries for 2 consecutive years

COUNTRY          YEAR 2001   YEAR 2000
-------          ---------   ---------
Austria           -            1.1
Belgium           -            1.2
France            1.5          1.3
Ireland           1.6          1.4

Then in 2002 - 2001

COUNTRY          YEAR 2002   YEAR 2001
-------          ---------   ---------
Austria           1.7          -
Belgium           1.8          -
France            1.9          1.5
Ireland           -            1.6

Finally 2003 - 2002

COUNTRY          YEAR 2003   YEAR 2002
-------          ---------   ---------
Austria           -           1.7          
Belgium           -           1.8          
France            -           1.9          
Germany           2.0         -
Italy             2.1         -

Thanks.

¿Fue útil?

Solución 2

for 2000/2001:

http://www.sqlfiddle.com/#!4/a2907/13 (corrected the duplicate aparition of country as Egor pointed out)

select 
   country, 
   max(case when year=2001 then to_char(amt) else '-' end) as 'YEAR 2001',
   max(case when year=2000 then to_char(amt) else '-' end) as 'YEAR 2000'
from 
  Rainfall
where year in (2000, 2001)
group by country
order by country;

If you want a generic query, this would do it, but without column names:

with (select 2000 as ref_year from dual) as s
select 
   country, 
   max(case when year=s.ref_year+1 then to_char(amt) else '-' end) as 'Next YEAR',
   max(case when year=s.ref_year   then to_char(amt) else '-' end) as 'YEAR'
from 
  Rainfall
where year in (s.ref_year, s.ref_year + 1)
group by country
order by country;

(you just change the ref_year in the subselect)

Otros consejos

SELECT * FROM Rainfall
pivot (max(AMT) for year in (2000, 2001, 2002, 2003))
order by 1

fiddle

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top