在SQL Server 2008中,我有一个表People(Id,Gender,Name)。 性别是男性还是女性。可能有许多同名的人。 我想写一个查询,为每个性别显示前2名 按计数和他们的数量,如下:
Male Female
Adam 23 Rose 34
Max 20 Jenny 15
我认为可能会使用PIVOT,但我看到的所有示例都只为每个标题显示一列。
答案 0 :(得分: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
答案 1 :(得分:0)
使用窗口功能。以下是使用临时表#people的完整解决方案。
- 使用temp db
使用tempdb;
去
- 跌落测试表
- 下表#people;
--go
- 创建测试表
create table #people(my_id int,my_gender char(1),my_name varchar(25));
去
- 清除测试表
从#people中删除;
- 三个计数
插入#people值
(23,'M','Adam'),
(34,'F','玫瑰');
去3
- 两个计数
插入#people值
(20,'M','Max'),
(15,'F','珍妮');
去2
- 一个计数
插入#people值
(20,'M','John'),
(15,'F','Julie');
去
- 按性别抓住前两名
;
用cte_Get_Top_Two作为
(
选择ROW_NUMBER()OVER(PAR_TION by my_gender ORDER BY count()DESC)AS my_window,
my_gender,my_name,count()为总数
来自#people
my_gender分组,my_name
)
从cte_Get_Top_Two中选择*,其中my_window在(1,2)中
去
这是输出。
PS:您可以从表中删除my_id,因为它与您的问题无关,但不会更改解决方案。