0

我有一份降雨数据列表

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

我将如何选择连续 2 年显示所有国家/地区

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

然后在 2002 - 2001 年

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

最后 2003 - 2002

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

谢谢。

4

2 回答 2

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

小提琴

于 2013-04-10T13:02:25.423 回答
3

2000/2001年:

http://www.sqlfiddle.com/#!4/a2907/13 (更正了 Egor 指出的国家的重复分隔)

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;

如果您想要一个通用查询,可以这样做,但没有列名:

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;

(您只需更改子选择中的 ref_year)

于 2013-04-10T12:59:46.870 回答