纵表变横表的小方法

来源:互联网 发布:免费 php cms 编辑:程序博客网 时间:2024/04/19 19:06

表一:populations

country        sex          population

-----------     --------     -----------------

中国                1                340

中国                2                260

美国                1                 45     

美国                2                 55

加拿大             1                 51

加拿大             2                 49

英国                1                 40

英国                2                 60

 

根据表一生产如下查询结果:

 

国家               男               女

-----------     --------     -----------

中国                340            260

美国                 45              55

美加拿大           51              49     

英国                 40              60

 

 

代码如下:

select country, sum(decode(sex,'1',num)) 男, sum(decode(sex,'2',num)) 女 from populations group by country;