[英]SQL Server difference between dates
I need to make a query that will compare the dates with the same 'ID_2' 我需要创建一个查询,将日期与相同的'ID_2'进行比较
If the difference between dates in column "ProdDateTime" is more than 7 and difference between dates in column "Sold" is more than 1 than it should show this rows. 如果“ProdDateTime”列中日期之间的差异大于7且“Sold”列中日期之间的差异大于1,则应显示此行。
here's an example: the difference between row #12 and #13 row with ID_2=444 is more than 7 in column ProdDateTime and is more than 1 in column Sold, that's why it should show this row as an error and all the following (14,15) because they have the same error. 这里有一个例子:第12行和第13行与ID_2 = 444之间的差异在列ProdDateTime中大于7,在列Sold中大于1,这就是为什么它应该将此行显示为错误以及以下所有内容(14 ,15)因为他们有同样的错误。
PS I used row_number
and dense_rank
to make ID_1
and ID_2
columns accordingly. PS我使用row_number
和dense_rank
地生成ID_1
和ID_2
列。
Do you have any tips on how to do so? 你有关于如何这样做的任何提示吗? Thank you all in advance! 谢谢大家!
I assumed that date in "ProdDateTime" column is always in increasing order. 我假设“ProdDateTime”列中的日期总是递增。 So, here we need to compare dates from previous row value and next row value of ProdDateTime column. 因此,这里我们需要比较ProdDateTime列的上一行值和下一行值的日期。 I have used LAG and LEAD analytical functions to solve this problem. 我使用LAG和LEAD分析函数来解决这个问题。 It's just a hint for you, I have implemented for only single condition below, Maybe it works for you:- 这只是对你的一个提示,我已经实现了下面的单一条件,也许它适合你: -
;WITH ResultData
AS
(
SELECT *
,LEAD(ProdDateTime) OVER (PARTITION BY ID_2 ORDER BY ID_2 ) AS Lead
,LAG(ProdDateTime) OVER (PARTITION BY ID_2 ORDER BY ID_2 ) AS Lag
,DATEDIFF(DAY, ProdDateTime, LEAD(ProdDateTime) OVER (PARTITION BY ID_2 ORDER BY ID_2 )) AS LeadDiff
,DATEDIFF(DAY, LAG(ProdDateTime) OVER (PARTITION BY ID_2 ORDER BY ID_2 ), ProdDateTime) AS LagDiff
FROM tb
)
SELECT *
FROM ResultData
WHERE LeadDiff > 1 OR LagDiff > 1
If you are unaware from above functions, Please do search for same. 如果您不了解上述功能,请搜索相同的功能。 Best of luck! 祝你好运!
You can select next
and previous
rows as the below. 您可以选择next
行和previous
一行,如下所示。
SELECT
* -- Your DATEDIFF operations
FROM
Tbl CurrentRow LEFT JOIN
Tbl PreviousRow ON CurrentRow.ID_1 = (PreviousRow.ID_1 + 1)
CurrentRow.ID_2 = PreviousRow.ID_2
LEFT JOIN
Tbl NextRow ON CurrentRow.ID_1 = (NextRow.ID_1 - 1)
CurrentRow.ID_2 = NextRow.ID_2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.