Cross Group By和Max Date Script

时间:2014-01-29 13:11:27

标签: sql sql-server

我正在编写一个脚本来从两个不同的表中提取Group By和MAX(Cre​​atedOnDate),但只返回table1的MAX(Cre​​atedOnDate)大于table2的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 个答案:

答案 0 :(得分: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