SQL 按日期分组有多个相同的结果

SQL Group by date with multiple same results

如何编写按日期对数据进行分组但显示数据首次更改时间的语句

日期 - 数据更改的时间

a,b,c - 一些数据,它可以是任何东西

date,a,b,c
04/26/2008,1,1,1
04/25/2008,1,2,1
04/24/2008,1,1,1
04/23/2008,1,1,1
04/22/2008,1,1,1
04/21/2008,2,2,2
04/20/2008,1,1,1

这应该是结果。它可能在不同的日期有相同的数据,但当数据保持不变时,它会在第二天丢失。

04/26/2008,1,1,1
04/25/2008,1,2,1
04/22/2008,1,1,1
04/21/2008,2,2,2
04/20/2008,1,1,1

它应该适用于 MS SQL Server 2008 r2

; with cte as 
(select *,
row_number() over (partition by a,b,c order by date asc) as rn
,row_number() over (order by date asc) as rn1
from yourtablename
)
select min(date) date,a,b,c from cte group by (rn1-rn),a,b,c
order by min(date) desc

检查下面link

For reference click here

这就像一个 gaps and islands problem.

 create table yourtablename ([date] date,a int,b int,c int);
insert into yourtablename values
 ('04/26/2008',1,1,1)
,('04/25/2008',1,2,1)
,('04/24/2008',1,1,1)
,('04/23/2008',1,1,1)
,('04/22/2008',1,1,1)
,('04/21/2008',2,2,2)
,('04/20/2008',1,1,1);

; with cte as 
(
select date, a,b,c,combinedstring=cast(a as varchar(max))+ cast(b as varchar(max))+ cast(c as varchar(max))
from yourtablename 
)
,cte2 as 
(select *,
rn1=row_number() over (partition by combinedstring order by date asc)
,rn2= row_number() over (order by date asc) 
from cte
)
select y.* 
from 
(
select date=min(date)
from cte2
group by (rn2-rn1),combinedstring) t
join yourtablename y
on t.date=y.date