---
title: "一条SQL查询"
author: "harrison2010"
date: "2009-02-12T17:13:09Z"
tags: []
slug: "sql"
draft: false
lastmod: "2009-02-12T17:13:09Z"
id: 327478
url: "https://harrison2010.iteye.com/blog/327478"
---

有一个表Studnet 
包含字段name(主键),sex,age,class 
现在求一条sql语句，并考虑执行效率 
想要得到的输出是 
class+男性age总和+女性age总和 

也就是说要得到一个班级中男的年龄和和女的年龄和。。。


select class,sum(case when sex = '男性' then age else 0 end) as 男性age总和, 
sum(case when sex = '女性' then age else 0 end) as 女性age总和 
from studnet

select class,sum(case when sex = '男性' then age else 0 end) as 男性age总和, 
sum(case when sex = '女性' then age else 0 end) as 女性age总和 
from studnet
group by class


select class,
sum(case when sex='男' then age else 0 end) as '男性age总和',
sum(case when sex='女' then age else 0 end) as '女性age总和'
from student
group by class


1,2楼是2000里最高效的了，2005可以用pivot 


SQL codeselect * from
    (select class,sex,age from Student) a
pivot
    (sum(age) for sex in (男,女)) b