表结构:
不可能选择删除日期最长的记录,这些记录按一个代码分组,但条件是全部删除。如果记录具有相同的代码,但具有不同的删除状态,则无需选择这些记录。 在此示例中,您选择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的经验。
答案 0 :(得分:0)
您可以通过代码对最大日期组使用内部联接
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
或者如果您不希望仅一行的代码获得结果,则可以使用
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
答案 1 :(得分:0)
请尝试: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
答案 2 :(得分:0)
尝试以下简单查询-:
select code,max(deleted_date) MAX_DeletedDate
from analyzes_test
group by code
having count(deleted_date)>1