在同一表的两个不同列中选择匹配的记录

时间:2018-08-16 14:22:51

标签: sql sql-server

我有两个类似下面的表,并且我需要下面的输出。 仅供参考-我大约有数百万条记录,因此我无法硬编码value =“ ***”

Col1 Col2 Col1_dtm Col2_dtm
a a 01/01/1900 03/01/1900 b c 01/01/1900 04/01/1900 c1 b 01/01/1900 02/01/1900 d1 g 01/01/1900 01/01/1900 e1 f 01/01/1900 06/12/1900 f d 01/01/1900 05/01/1900 c 01/01/1900 01/01/1900 d 01/01/1900 01/01/1900 e 01/01/1900 01/01/1900 g 01/01/1900 01/01/1900

我需要如下输出

Col1 Col2 Col2_dtm-col1_dtm
a a 59 (days) b b 31 (days) c c 90 (days) d d 120 (days) f f 162 (days) g g 0 (days)

1 个答案:

答案 0 :(得分:1)

尝试一下:

select t1.col1,
       t2.col2,
       datediff(day, t1.col1_dtm, t2.col2_dtm)
from my_table t1
join my_table t2 on t1.col1 = t2.col2