表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
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