我需要编写一个查询来查找C
列Type
中值AND
的所有记录,它不是最新日期。例如,在Table1
中,值C
应该是最新日期,但John Smith也有B
之后的A
和2014-02-01
类型。 Joana和Brian都不会出现在结果中。
人:
FirstName LastName DOB Type Date
John Smith 01/01/1992 C 2014-02-01
John Smith 01/01/1992 B 2014-05-01
John Smith 01/01/1992 A 2014-04-01
Joana Doe 05/14/1971 A 2014-07-01
Joana Doe 05/14/1971 C 2014-09-01
Brian Holden 12/01/1992 A 2014-08-01
我甚至完全不知道该做什么。这就是我的想法:
SELECT FirstName, LastName, DOB
FROM Table1
GROUP BY FirstName, LastName, DOB
HAVING COUNT(LastName) > 1 AND Type='C'
关于我可以尝试的任何提示都会有所帮助!
答案 0 :(得分:1)
select firstname, lastname, dob from table1 left join
(select max(date) as maxdate from table1) as m on table1.date=m.maxdate
where table1.Type='C' and m.maxdate is null;
在第二个表的连接字段中,where子句需要null的左连接是一个模式,它在第一个表中找不到所有的,在这种情况下是最大日期。
答案 1 :(得分:0)
您可以使用row_number()
:
select p.*
from (select p.*, row_number() over (partition by firstname, lastname, dob order by date desc) as seqnum
from person
where type = 'C'
) p
where seqnum > 1;
编辑:
我认为,我误解了这个问题。您需要在最新C
日期之后的记录。这个想法很相似,使用max()
代替row_number()
:
select p.*
from (select p.*,
max(case when type = 'C' then date end) over (partition by firstname, lastname, dob) as maxcdate
from person
where type = 'C'
) p
where date > maxcdate and type <> 'C';
答案 2 :(得分:0)
您可以使用exists
检查日期更长的另一行
select FirstName, LastName, DOB
from Table1 t1
where Type = 'C'
and exists (
select 1 from Table1 t2
where t2.FirstName = t1.FirstName
and t2.LastName = t1.LastName
and t2.DOB = t1.DOB
and t2.Date > t1.Date
)
或者您可以按查询
修改原始群组SELECT FirstName, LastName, DOB
FROM Table1
GROUP BY FirstName, LastName, DOB
HAVING MAX(Date) > MAX(CASE WHEN Type = 'C' THEN Date END)