2014-01-29 17 views
0

我正在編寫一個腳本來從兩個不同的表中抽取Group By和MAX(Cre​​atedOnDate),但只返回table1的MAX(Cre​​atedOnDate)大於表2的MAX(Cre​​atedOnDate)的位置。交叉分組和最大日期腳本

例如;

select MasterId, max(createdon) --Master id + latest product generated date 
from product 
group by MasterId 

select contactId, max(createdon) --Contact id + latest edit date for that contact 
from contactEdit 
group by contactId 

    from contactEdit ce 
join contactmaster cm 
    on ce.contactId = cm.contactid 
join product p 
    on p.MasterId = cm.MasterId 

在這兩個表之間有一個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