2014-01-29 2 views
0

두 테이블에서 Group By과 MAX (CreatedOnDate)를 가져 오는 스크립트를 작성 중이지만 table1의 MAX (CreatedOnDate)가 table2의 MAX (CreatedOnDate)보다 큰 경우에만 반환합니다.그룹 간 및 최대 날짜 스크립트

예 :

이 두 테이블 사이에는 contactMaster 테이블이 있으며,이 테이블의 조인은 위에 있습니다. 해당 연락처와 관련하여 마지막 제품이 생성 된 이후 편집 된 모든 연락처 목록을 찾고 싶습니다.

같은 것;

where max(ce.createdon) > max(p.createdon) 

답변

1

표가 어떻게 보이고 정확히 무엇을 달성하려고하는지 잘 모르므로 이는 약간의 추측입니다. 당신이하고 싶은

그룹 부속 선택의 테이블은 다음 maxdates 비교 :

with ce as (
    select MasterId, max(createdon) maxco --Master id + latest product generated date 
    from product 
    group by MasterId 
) 
, prod as (
    select contactId, max(createdon) maxco --Contact id + latest edit date for that contact 
    from contactEdit 
    group by contactId 
) 
, cm as (
    select contactId, masterId, max(createdon) maxco --Master id + latest product generated date 
    from contactmaster 
    group by contactId, masterId 
) 
select contactId 
    from ce 
join cm 
    on ce.contactId = cm.contactid 
join product p 
    on p.MasterId = cm.MasterId 
where ce.maxco > prod.maxco