sql select 语句检查相同 id 的先前记录

sql select statement to check for previous records for same id

我正在尝试构建一个查询,该查询将检查为当前日期添加的记录。我想为每条记录取唯一的 company_id 并检查每个 company_id 的历史记录是否存在几乎相同的 document_date (上一年:[=21= .: 文档日期是 2014/12/31,之前的记录应该是 2013/21/31).

到目前为止,我已经能够从当前添加的记录中提取每条 company_id 并显示特定文档类型可用的最新文档日期是什么

在伪代码中:

select company_id, MAX(document_date), document_type
from submissions
where company_id in
(
select distinct company_id
from submissions
where filing_date = current date
)
and document_type = 'annual'
group by company_id, document_type

我希望能够从当前添加的记录中获取 document_type 值并检查具有相同值的先前记录,但如前所述 document_date 是前一年的记录.我是否需要为此建立一个程序,或者是否可以在 select 语句中完成?

想法是 SELECT 来自当前日期的提交 table 的文档,并将其交叉(或外部)应用到同一 [=18] 的提交 table =] 和 document_type 其中 filing_date 是从当前日期算起的年份:

select s.*, x.*
from submissions s
cross apply (
  select top (1) *
  from submissions s2
  where s.company_id = s2.company_id
  and s.document_type = s2.document_type
  and s.filing_date = dateadd(year, 1, s2.filing_date)
) x
where filing_date = @current_date

请将'*'替换为所需的列名。

TOP (1) 在这里只是从子查询中提取一行。

试试这个:

; WITH cte AS (
  SELECT company_id
       , document_date
       , document_type
       , Row_Number() OVER (PARTITION BY company_id ORDER BY document_date DESC) As sequence
  FROM   submissions
  WHERE  document_type = 'Annual'
)
SELECT current_record.company_id
     , current_record.document_date
     , current_record.document_type
     , next_record.document_date As next_record_document_date
     , next_record.document_type As next_record_document_type
FROM   cte As current_record
 LEFT    /* outer join as we might not always have a "next" result */
  JOIN cte As next_record
    ON next_record.company_id = current_record.company_id
   AND next_record.sequence   = current_record.sequence + 1
WHERE  current_record.sequence = 1 /* Limit to the "first" record */
AND    current_record.filing_date = Current_Timestamp
;

这使用窗口函数 Row_Number() 为每条记录分配一个...行号...。 PARTITION BY 子句为每个 company_id 重置此行号。行号的顺序由该函数的 ORDER BY 部分决定(即由 document_date DESC)。

一旦我们有了这些信息,我们就可以执行自连接,将 "current" 和 "next" 记录连接在一起。

select s1.company_id, s1.document_date, s2.document_date
  from submissions s1 
  join submissions s2
    on s2.company_id = s1.company_id 
   and s2.document_date = dateadd(yy, -1, s1.document_date) 
   and s2.document_type = 'annual'
   and s1.document_type = 'annual'