create table #
(时间 varchar(10), 货物名单 varchar(10))
insert into #
select '8:00', '西瓜' union all
select '8:01', '西瓜' union all
select '8:02', '西瓜' union all
select '8:03', '西瓜' union all
select '8:05', '西瓜' union all
select '8:55', '西瓜' union all
select '8:56', '香蕉' union all
select '8:57', '香蕉' union all
select '8:57', '西瓜' union all
select '8:58', '苹果' union all
select '8:59', '苹果' union all
select '9:58', '西瓜' union all
select '9:59', '西瓜'
--第一种
select 货物名单,count(col)as '次数'
from
(
select
*,col=(select count(1) from # where 时间<a.时间 and 货物名单<>a.货物名单)
from # a
)a
group by col,货物名单
/*
货物名单 次数
---------- -----------
苹果 2
西瓜 6
西瓜 1
西瓜 2
香蕉 2
(所影响的行数为 5 行)
*/
--第二种
select 货物名单,count(col)as '次数',min(时间)+'-'+max(时间)
from
(
select
*,col=(select count(1) from # where 时间<a.时间 and 货物名单<>a.货物名单)
from # a
)a
group by col,货物名单
/*
货物名单 次数
---------- ----------- ---------------------
苹果 2 8:58-8:59
西瓜 6 8:00-8:55
西瓜 1 8:57-8:57
西瓜 2 9:58-9:59
香蕉 2 8:56-8:57
(所影响的行数为 5 行)
*/