高难度啊!!!请问怎么样把相同数据一起统计、合并显示?
company与name相同的数据出现的次数,并一起显示最新的数据,按次数多少进行排序,以company与name排序
id company name Product Mark date
1 A YY 1 H 2008-11-3
2 A HFF 2 Y 2008-11-3
3 B JGR 1 H 2008-11-5
4 C NYJ 3 U 2008-11-5
5 B NRM 1 O 2008-11-6
6 A YY 2 P 2008-11-7
7 A YY 2 Y 2008-11-8
8 B JGR 1 Y 2008-11-8
上表的统计结果应为
id company name Product Mark date count
7 A YY 2 Y 2008-11-8 3
8 B JGR 1 Y 2008-11-8 2
2 A HFF 2 Y 2008-11-3 1
3 B JGR 1 H 2008-11-5 1
4 C NYJ 3 U 2008-11-5 1
即,每A公司的YY职员一共来了3次,显示最后日期的记录+次数。
=====================================================================================
-->生成测试数据
declare @t table(id int,company varchar(10), name varchar(10), Product int, Mark varchar(10),date datetime)
insert @t select 1,'A','YY',1,'H','2008-11-3'
insert @t select 2,'A','HFF',2,'Y','2008-11-3'
insert @t select 3,'B','JGR',1,'H','2008-11-5'
insert @t select 4,'C','NYJ',3,'U','2008-11-5'
insert @t select 5,'B','NRM',1,'O','2008-11-6'
insert @t select 6,'A','YY',2,'P','2008-11-7'
insert @t select 7,'A','YY',2,'Y','2008-11-8'
insert @t select 8,'B','JGR',1,'Y','2008-11-8'
-->开始查询
select
*,
[count]=(select count(1) from @t where company=t.company and name=t.name)
from @t t
where not exists(
select 1
from @t
where company=t.company and name=t.name and date>t.date)
order by [count] desc
相同数据一起统计、合并
最新推荐文章于 2025-08-22 10:24:20 发布