在sql存储过程中取多个列的平均值

时间:2014-02-17 08:29:10

标签: sql sql-server stored-procedures

我有一张表格如下:

Age Gender Shoesize
1   Male    121
2   Female  130
2   Female  138
2   m   147
2   Male    130
2   Male    138
3   Female  130
3   Female  138
3   Female  147
3   Female  155
3   Female  164
3   Female  172
3   Male    130
3   Male    138
3   Male    147
3   Male    155
3   Male    164
3   Male    172
3   Male    181
3   Male    189
4   f   147
4   f   155
4   f   164
4   f   172
4   f   181
4   F   281
4   Female  138
4   Female  147
4   Female  155
4   Female  164
4   Female  172
4   Female  181
4   Female  189
4   Female  197
4   m   130
4   m   147
4   m   155
4   m   164
4   m   172
4   m   181
4   Male    121
4   Male    147
4   Male    155
4   Male    164
4   Male    172

我希望显示所有年龄= 1的男性,对于特定鞋子的男性的平均鞋码大小与女性相同。

       Males          Females
Age  ShoeSize(Avg)  ShoeSize(Avg)

请帮助我是SQL

的新手
    Select Age, ChildGender, Shoesize, AVG(Shoesize) from [dbo].[Transaction]

GROUP BY Age , ChildGender, Shoesize 

修改

我是如何将这两个查询结合起来的

 Select AVG(Shoesize) AS AverageShoeSizeMale, Age from [dbo].[Transaction] where ChildGender = 'm' or ChildGender = 'male' Group by Age ORDER BY Age DESC



 Select AVG(Shoesize) AS AverageShoeSizeFemale, Age from [dbo].[Transaction] where ChildGender = 'f' or ChildGender = 'female' Group by Age ORDER BY Age DESC 

2 个答案:

答案 0 :(得分:1)

您的任务答案如下:

select age,
       (select avg(ShoeSize) from [table] t2 where t2.age = t1.age and t2.Gender='Male') as avg_male,
       (select avg(ShoeSize) from [table] t2 where t2.age = t1.age and t2.Gender='Female') as avg_female
from [table] t1
group by ide

但是,我不建议使用子查询。我不确定是否有可能在这种任务中避免它们。

更好的方法是从普通表中获取数据并使用它们:

select age, Gender, AVG(ShoeSize)
from [table]
group by age, Gender
order by age

答案 1 :(得分:0)

尝试这个..

SELECT AGE , MALE,FEMALE,,(MALE+FEMALE)/CAST(2 AS DECIMAL(5,3)) [AVG]
 from [dbo].[Transaction] PIVOT ( AVG(Shoesize ) FOR GENDER IN (male,female)) AS PVT
ORDER BY AGE