请问一个分组统计的sql语句
请教一个分组统计的sql语句
表结构如下
ID clientID s1
1 1 a
2 1 b
3 2 a
4 1 c
我想按s1分组,统计clientID的数量,但是如果clientID相同,就只认其最新的s1值,上表结果应该是
count s1
1 c
1 a
其中ID是自增字段
该如何实现呢?
------解决思路----------------------
------解决思路----------------------
感觉是这样的
表结构如下
ID clientID s1
1 1 a
2 1 b
3 2 a
4 1 c
我想按s1分组,统计clientID的数量,但是如果clientID相同,就只认其最新的s1值,上表结果应该是
count s1
1 c
1 a
其中ID是自增字段
该如何实现呢?
------解决思路----------------------
-- 先按 clientid 取最新的数据,再对结果进行分组。
if exists(select * from sysobjects where xtype ='u' and name = 'mytest')
drop table mytest
go
create table mytest(id int , clientid int , s1 varchar(10))
go
insert into mytest values
(1,1,'a'),
(2,1,'b'),
(3,2,'a'),
(4,1,'c')
go
with m as
(
select ROW_NUMBER() over(partition by clientid order by id desc ) as rn , id,clientid , s1
from mytest
)
select s1 , COUNT(*) as [count] from m where rn = 1 group by s1
go
(4 行受影响)
s1 count
---------- -----------
a 1
c 1
(2 行受影响)
------解决思路----------------------
感觉是这样的
select count(*) as [count],s1 from (
select *,row_number() over(partition by clientID order by ID desc) as rId from tablename
) where rId=1 group by s1