【问题标题】:Cross Group By and Max Date ScriptCross Group By 和 Max Date 脚本
【发布时间】:2014-02-21 07:35:43
【问题描述】:

我正在编写一个脚本来从两个不同的表中提取一个Group By 和一个 MAX(CreatedOnDate),但只返回 table1 的 MAX(CreatedOnDate) 大于 table2 的 MAX(CreatedOnDate)。

例如;

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表,它的join也在上面。我想查找自上次创建与该联系人相关的产品以来进行过编辑的所有联系人的列表。

类似的东西;

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

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    我不太确定您的表格是什么样的以及您想要实现的具体目标,所以这有点猜测。

    您要做的是将表分组在子选择中,然后比较最大日期:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-19
      相关资源
      最近更新 更多