SQL删除ID和月份级别的重复项
我有一张这样的桌子:SQL删除ID和月份级别的重复项,sql,Sql,我有一张这样的桌子: ID日期名称年龄 1 2015年4月10日第24节 1 2015年4月28日Theja1 26 1 2015年7月14日Theja2 45 1 2015年7月30日Theja2 45 1 2015年8月30日Theja3 54 2 2016年4月10日Jaya 23 2016年4月28日Jaya 23 2016年5月14日Jaya1 65 2016年5月2日30日日本航空65 但我希望输出如下: ID日期名称年龄 1 2015年4月28日Theja1 26 2015年5月1
ID日期名称年龄
1 2015年4月10日第24节
1 2015年4月28日Theja1 26
1 2015年7月14日Theja2 45
1 2015年7月30日Theja2 45
1 2015年8月30日Theja3 54
2 2016年4月10日Jaya 23
2016年4月28日Jaya 23
2016年5月14日Jaya1 65
2016年5月2日30日日本航空65
但我希望输出如下:
ID日期名称年龄
1 2015年4月28日Theja1 26
2015年5月1日Theja1 26
2015年6月1日Theja1 26
1 2015年7月30日Theja2 45
1 2015年8月30日Theja3 54
2016年4月28日Jaya 23
2016年5月2日30日日本航空65
考虑每个月的1个记录,即最大值,如果缺少任何月份,则考虑以前的记录填充缺失月份。
< P>不同的数据库处理日期的方法不同。以下是每月获取一行的ANSI标准方法:select id, min(date)
from t
group by id,
extract(year from date), extract(month from date);
我已经尝试了一个解决方案,并提供了以下内容,但是您需要一个日历表来在输出中插入缺少的行。 这里给出了基于SQL Server的解决方案 数据设置:
create table temptable (
id int,
[date] date,
name varchar (50),
age int
);
insert into temptable values
(1,'04-10-2015','Theja',24)
insert into temptable values
(1,'04-28-2015','Theja1',26)
insert into temptable values
(1,'07-14-2015','Theja2',45)
insert into temptable values
(1,'07-30-2015','Theja2',45)
insert into temptable values
(1,'08-30-2015','Theja3',54)
insert into temptable values
(2,'04-10-2016','Jaya',23)
insert into temptable values
(2,'04-28-2016','Jaya',23)
insert into temptable values
(2,'05-14-2016','Jaya1',65)
insert into temptable values
(2,'05-30-2016','Jaya1',65)
以下解决方案完成,直到出现重复问题。但要获得缺少的行,需要实现日历表。
您可以加入日历表,然后使用cte3的输出来获取缺少的数据
with cte1 as (
select *,
row_number() over ( partition by month([date]) order by [date]) as rownm,
concat(id,format([date],'MMyyyy')) as unqcol
from temptable
) , cte2 as
(
select unqcol, max(rownm) as maxdt
from cte1
group by unqcol
), cte3 as
( select a.*, lead(a.[date]) over (partition by a.id order by a.id,a.[date]) as NextDate from
cte1 a inner join cte2 b
on a.unqcol=b.unqcol and a.rownm=b.maxdt
)
select c.id,c.[date],c.name,c.age,c.NextDate from cte3 c
order by c.[date]
用您正在使用的数据库标记您的问题。另外,提供所需的结果集。