我的数据库中有两个表
表1:
caseId name ApprovalDate ApprovalSatus
150150 John 2018-01-29 41
150151 Dave 2018-01-02 41
表2:
contId StatusSourceNoKeyId Status contractDate
210210 38^|^150150^|^31796794 41 2018-02-01
210211 38^|^150150^|^31796797 40 2018-01-28
210220 38^|^150151^|^31796720 41 2018-01-03
当表1中的CaseId类似
时,我需要找出Table2中的contractDate
和Table1中的ApprovalDate
之间的日期差异
表2中的'38 ^ | ^ caseId ^ | ^ 31796794',状态为'41'。
我该如何做这样的选择?
谢谢,
答案 0 :(得分:0)
为方便起见,我已将查询更改为公用表表达式。您可以使用实际表格。
;WITH CTE1
AS
(
SELECT '150150' caseId, 'John' Name, '2018-01-29' ApprovalDate, 41 'ApprovalSatus' UNION
SELECT '150151' ,'Dave' ,'2018-01-02' , 41
)
, CTE2
AS
(
SELECT 210210 contId, '38^|^150150^|^31796794' StatusSourceNoKeyId, 41 Status, '2018-02-01' contractDate UNION
SELECT 210211 ,'38^|^150150^|^31796797', 40 ,'2018-01-28' UNION
SELECT 210211 ,'38^|^150152^|^31796797', 40 ,'2018-01-28' UNION
SELECT 210220 ,'38^|^150151^|^31796720', 41 ,'2018-01-03'
)
SELECT CTE1.caseId, DATEDIFF(DD, cte1.ApprovalDate, cte2.contractDate) DatDiff FROM CTE1 INNER JOIN CTE2 ON
CTE2.StatusSourceNoKeyId LIKE '%^'+CTE1.caseId+'^%'
WHERE CTE2.Status = '41'
在您的情况下,查询可能类似于
SELECT Tablle1.caseId, DATEDIFF(DD, Tablle1.ApprovalDate, Tablle2.contractDate) DatDiff FROM Tablle1 INNER JOIN Tablle2 ON
Tablle2.StatusSourceNoKeyId LIKE '%^'+Tablle1.caseId+'^%'
WHERE Tablle2.Status = '41'
答案 1 :(得分:0)
在SQL-Server中,您拥有DATEDIFF函数
快速示例:
select
DATEDIF(day, b.contractDate, a.ApprovalDate) as difference, *
from Table1 a
left join
Table2 b on b.StatusSourceNoKeyId like '%^'+ a.caseId +'^%'
and a.ApprovalStatus = b.Status
这应该有效,但我还没有测试过它。