日期:2014-05-17  浏览次数:20528 次

求一个group的sql查询,标题要长点
表table
id name group leader
1  aa 一组  0
2  bb 一组  1
3  cc 二组  0
4  dd 二组  1
5  ee 二组  0
6  ff 三组  0
7  gg 三组  0

返回
id name group leader 统计
2  bb 一组  1  2
4  dd 二组  1  3
6  ff 三组  0  2

说明
按group分组,取出每组中第一条数据,优先取leader=1的,没有则取id最小的,并统计每组成员人数
不知道说清楚没有,求大神
sql

------解决方案--------------------

with tb (id, name, [group], leader)as(
select 1,  'aa', '一组',  0 union all
select 2,  'bb', '一组',  1 union all
select 3,  'cc', '二组',  0 union all
select 4,  'dd', '二组',  1 union all
select 5,  'ee', '二组',  0 union all
select 6,  'ff', '三组',  0 union all
select 7,  'gg', '三组',  0),
tbb as(
select *,row_number() over(partition by [group] order by leader desc,id  ) number from tb)
select id,name,[group],leader,
(select count([group]) from tbb where a.[group]=[group]) 统计 from tbb a where number=1
order by id

------解决方案--------------------
select *,统计=(select COUNT(1) from tb t2 where t2.[group]=t1.[group]) from tb t1 where id= (select top 1 id from tb t2 where t2.[group]=t1.[group] order by t2.leader desc,t2.id asc)