group by +计算不同的列值

时间:2015-02-20 15:59:12

标签: sql sql-server-2008 group-by

我有一个简单的表id, gender, age and favoriteMovie

性别列仅包含男性和女性的值。

我想显示电影专栏中的所有电影片段(按电影分组)和两个单独的列中显示选定电影的男性人数和女性人数。

count(gender = 'male') as male, count(gender = 'female') as female

这样的东西

数据库是ms-sql 2008

任何消化都非常感激

2 个答案:

答案 0 :(得分:1)

您可以使用案例语法(将count更改为sum):

   select favoriteMovie as movie, 
          sum(case 
                when gender = 'male' then
                  1
                else
                  0 
              end) as male,
          sum(case 
                when gender = 'female' then
                  1
                else
                  0 
              end) as female
    from MyTable
group by favoriteMovie 

答案 1 :(得分:0)

枢轴不太好,但这对我有用。

declare @t table (id varchar(55),gender varchar(55),age varchar(55),favoriteMovie varchar(55))

insert into @t values(1,'m',16,'star wars')
insert into @t values(2,'f',16,'star trek')
insert into @t values(3,'m',16,'star trek')
insert into @t values(4,'f',16,'star wars')
insert into @t values(5,'m',16,'star wars')

然后查询。

select favoriteMovie, sum([m]) as "m",sum([f]) as "f"
from @t
    pivot 
    (
    count(gender)
    for gender in ([m],[f])
    ) as pt
group by favoriteMovie