0

在 SQL Server 2008 中,我有一个表 People(Id、Gender、Name)。性别为男性或女性。可以有很多人同名。我想编写一个查询,按计数及其计数为每个性别显示前 2 个名称,如下所示:

  Male        Female
Adam   23    Rose  34
Max    20    Jenny 15

我认为可能会使用 PIVOT,但我看到的所有示例都只显示每个标题的一列。

4

2 回答 2

1

这是关于 SQL Fiddle 的示例——http://sqlfiddle.com/#!3/b3477/ 1

这使用了几个常见的表格表达式来分隔性别。

create table People 
(
 Id int, 
 Gender varchar(50), 
 Name varchar(50)
)
;

insert into People values (1, 'Male', 'Bob');
insert into People values  (2, 'Male', 'Bob');
insert into People values  (3, 'Male', 'Bill');
insert into People values (4, 'Male', 'Chuck');

insert into People values (5, 'Female', 'Anne');
insert into People values (6, 'Female', 'Anne');
insert into People values (7, 'Female', 'Bobbi');
insert into People values (8, 'Female', 'Jane');

with cteMale as
(

    select Name as 'MaleName', Count(*) as Num, ROW_NUMBER() over(order by count(*) desc, Name) RowNum
    from People 
    where Gender = 'Male'
    group by Name

)
,
 cteFemale as
(
  select top 2 Name as 'FemaleName', Count(*) as Num, ROW_NUMBER() over(order by count(*) desc, Name) RowNum
  from People 
  where Gender = 'Female'
  group by Name

)

select a.MaleName, a.Num as MaleNum, b.femaleName, b.Num as FemaleNum
from cteMale a
  join cteFemale b on 
    a.RowNum = b.RowNum
where a.RowNum <= 2
于 2013-08-13T15:46:52.783 回答
0

使用窗口函数。下面是使用临时表#people 的完整解决方案。

-- 使用临时数据库
使用临时数据库;

-- 删除测试表
--drop table #people;
- 去

-- 创建测试表
create table #people (my_id int, my_gender char(1), my_name varchar(25));

--从#people中清除测试表
删除;

-- 三个计数
插入#people 值
(23,'M','Adam'),
(34,'F','Rose');
去 3

--将两个计数
插入#people值
(20,'M','Max'),
(15,'F','Jenny');
去 2

-- 一个计数
插入 #people 值
(20, 'M', 'John'),
(15, 'F', 'Julie');

——按性别抢前两名

与 cte_Get_Top_Two 为
(
select ROW_NUMBER() OVER(PARTITION BY my_gender ORDER BY count( ) DESC) AS my_window,
my_gender, my_name, count(
) 总计
来自 #people
group by my_gender, my_name
)
select * from cte_Get_Top_Two where my_window in (1 , 2)


这是输出。

在此处输入图像描述

PS:您可以从表中删除 my_id ,因为它与您的问题无关,但不会更改解决方案。

于 2013-08-13T15:32:00.120 回答