从重复行中选择最大已删除的\u数据

0lvr5msh  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(267)

表结构:

不能选择具有最大删除日期的记录,这些记录按一个代码分组,条件是它们全部被删除。如果记录的代码相同,但删除状态不同,则不需要选择这些记录。在本例中,选择id=3、id=4的记录。

SELECT * FROM analyzes_test WHERE code IN (SELECT code FROM analyzes_test GROUP BY code HAVING count(code)>1) AND deleted = (max deleted_date)

但我不知道如何用最长的日期来代替删除。请告诉我谁对sql有更多的经验。

l2osamch

l2osamch1#

尝试以下简单查询-:

select code,max(deleted_date) MAX_DeletedDate
  from analyzes_test  
group by code 
  having count(deleted_date)>1
uurity8g

uurity8g2#

您可以在max date group by code上使用内部联接

select * 
FROM analyzes_test a
inner join  (
  select code, max(deleted_date) max_date 
  FROM analyzes_test 
  group by code  
)  t on t.max_date = a.deleted_date and t.code = a.code

或者如果您不希望代码的结果只有a可以使用的行

select * 
FROM analyzes_test a
inner join  (
  select code, max(deleted_date) max_date 
  FROM analyzes_test 
  group by code  
  having count(*)>1
)  t on t.max_date = a.deleted_date and t.code = a.code
1hdlvixo

1hdlvixo3#

试试这个: GROUP BY 以及 HAVING 将有助于检索每个代码的最大日期并将其用作 subquery 要检索表的所有信息,请执行以下操作:

SELECT ant.* 
FROM analyzes_test ant
INNER JOIN (SELECT code, MAX(deleted_date) max_date 
        FROM analyzes_test 
        WHERE deleted_date IS NOT NULL
        GROUP BY code
        HAVING COUNT(deleted_date) > 1) t ON t.code = ant.code 
    AND t.max_date = ant.deleted_date

相关问题