获取字段数的最新日期

时间:2016-10-19 12:34:39

标签: sql join

我有两个要加入的表

  

CustomerID的订阅   报告提取列CustomerId and ReportDt

我希望将结果作为列

CustomerId   LastReportPullDt    ReportCount

其中

  

LastReportPullDt =最新报告截止日期
  ReportCount =客户报告计数

我的条件是检查在Report Pull表中创建了今天记录的客户,并且该客户应该至少有另一条记录存在,以便今天提取的报告是第二次或第n次报告已被提取其中n> 1。

  

示例数据
  表订阅

CustomerId

C1
C2
C3
C4

报告拉动表
CustomerId ReportDt

C1            19-Oct-2016
C1            01-Oct-2016
C1            17-Sep-2016
C2            18-Oct-2016
C2            01-Sep-2016
C3            19-Oct-2016

查询仅返回C1作为记录,最新日期为10月19日,3作为计数。 这是因为只有C1满足今天的报告日期,并且对于否则计数> 1。报告。

4 个答案:

答案 0 :(得分:1)

此查询仅返回上次运行报告的客户,并且总共运行报告多次

SELECT C.Id,
       MAX(RP.PullDt) as LastReportPullDt, 
       COUNT(*) AS ReportCount
 FROM Customer C
 INNER JOIN ReportPull RP ON C.CustomerId = RP.CustomerId
 GROUP BY C.CustomerId
 HAVING COUNT(*) > 1 -- MORE THAN ONE ATTEMPT AT RUNNING THE REPORT
 AND MAX(RP.PullDt) >= dateadd(dd,0, datediff(dd,0,GETUTCDATE())) -- THE LAST ATTEMPT IS TODAY

仅供参考,此部分:

dateadd(dd,0, datediff(dd,0,GETUTCDATE()))

只是删除从GETUTCDATE()返回的日期/时间的时间,以便您比较从今天开始(即午夜)开始的所有报告。

答案 1 :(得分:0)

尝试:

select * from (
  select 
    customerid, 
    max(reportdt) as LastReportPullDt, 
    count(*) as ReportCount 
  from "Report Pull" 
  group by customerid
) where LastReportPullDt='2016-10-19' and ReportCount>1

答案 2 :(得分:0)

; with temp as 
(
    select  s.CustomerId, ReportDt, Rank() over (partition by s.CustomerId order by ReportDt desc) r
    from    Subscription    s
    join    ReportPull  r   on s.CustomerId = r.CustomerId
)
    select  *
    from    temp
    where   r = 1

答案 3 :(得分:0)

尝试这样的事情。

如果您不需要customer_name,则可以避免使用连接部分。

select
    reports.customer_id
    , count(reports.*) as num_records
    , max(ReportDt)
    , customers.customer_name
from reports
    left join customers
        on reports.customer_id = customers.customer_id
group by 
    reports.customer_id, customers.customer_name
having 
    count(*) >= min_required_reports