使用聚合函数计算多行中的唯一值

时间:2014-06-05 00:32:45

标签: sql count aggregate

这是一个帮助说明问题的示例数据库: 想象一下包含以下信息的数据库

Color| State| Age
---------------
black neutered  3
black neutered  4
white neutered 6
white non-neutered 8
black non-neutered 4

我想以下列方式显示此数据库中的信息:

Color| Total  Count |  Total neutered  | Total Non-neutered  | Neutered Ave Age | Non-neutered Ave Age
black| 3 | 2 | 1 | 3.5 | 4
white| 2 | 1 | 1 | 8| 4

我写的声明:

select color, 
count(color), 
SUM (case when state='neutered' then 1 else 0 end) as 'Total neutered',
SUM (case when state='non-neutered' then 1 else 0 end) as 'Total non-neutered',
'Neutered Ave Age' = case when state='neutered' then AVG(age) end,
'Non-Neutered Ave Age' = case when state='non-neutered' then AVG(age) end,
from cats
group by color, state

当我运行这些查询时,它会分离数据

black| 2 | 2 | 0 | 3.5 | 0
black| 1 | 0 | 1 | 0 | 4
white| 2 | 1 | 0 | 8| 0
white| 2 | 0 | 1 | 0| 4

我无论如何都无法解决这个问题?

1 个答案:

答案 0 :(得分:0)

据推测,您不希望state中有group by,而您需要修复avg()

select color, count(color), 
       SUM(case when state = 'neutered' then 1 else 0 end) as TotalNeutered,
       SUM(case when state = 'non-neutered' then 1 else 0 end) as TotalnonNeutered,
       AVG(case when state = 'neutered' then age end) as NeuteredAge,
       AVG(case when state = 'non-neutered' then age end) as nonNeuteredAge
from cats
group by color;

将列别名放在单引号中也是不好的做法。单引号只能用于字符串和日期常量。