SQL删除ID和Month级别的重复项

问题描述 投票:-1回答:2

我有一个像这样的表:

ID Date Name Age 1 10/04/2015 Theja 24 1 28/04/2015 Theja1 26 1 14/07/2015 Theja2 45 1 30/07/2015 Theja2 45 1 30/08/2015 Theja3 54 2 10/04/2016 Jaya 23 2 28/04/2016 Jaya 23 2 14/05/2016 Jaya1 65 2 30/05/2016 Jaya1 65

但我希望输出如下:

ID Date Name Age 1 28/04/2015 Theja1 26 1 01/05/2015 Theja1 26 1 01/06/2015 Theja1 26 1 30/07/2015 Theja2 45 1 30/08/2015 Theja3 54 2 28/04/2016 Jaya 23 2 30/05/2016 Jaya1 65

考虑每个月最多1条记录,如果缺少任何ID,则考虑以前的记录填写缺失的月份。

sql
2个回答
0
投票

不同的数据库有不同的处理日期的方法。以下是每月获得一行的ANSI标准方法:

select id, min(date)
from t
group by id,
         extract(year from date), extract(month from date);

0
投票

我试过一个解决方案,并提供以下内容,但您需要一个日历表来在输出中插入缺少的行。这里给出基于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]
© www.soinside.com 2019 - 2024. All rights reserved.