寻找过去三年未与我们开展服务业务的客户

时间:2019-06-19 13:51:16

标签: sql max dateadd

我正在尝试查找超过3年的最新客户发票,但是在对照实际记录检查我的结果之后,服务标题表中的发票比3年新。

使用SQL Management Studio

    select [No_] as 'Customer No.', 
    sih.[Name],  
    max(sih.[No_]) as 'Last Service Invoice No.', 
    max(sih.[Posting Date]) as 'Last Service Order'
    from [Service Invoice Header]sih 
    left join [Customer] c on sih.[Customer No_] = c.[No_]


    group by c.[No_], sih.name

    having max(sih.[Posting Date]) <  DATEADD(YEAR, -3, GETDATE())
    order by sih.name

我希望每个已开具发票的客户的上次服务发票过帐日期都早于3岁。

1 个答案:

答案 0 :(得分:0)

您似乎想要:

select sih.*
from [Service Invoice Header] sih 
where sih.[Posting Date] = (select max(sih2.[Posting Date])
                            from [Service Invoice Header] sih2
                            where sih2.[Customer No_] = sih.[No_] and
                                  sih2.[Posting Date]) < DATEADD(YEAR, -3, GETDATE())
                           );

您没有从客户表中选择列,因此似乎不需要。如果确实需要,可以将其添加到外部查询中。