下面我有一些简单的记录。
CREATE TABLE TEMPS
(
ID INT,
ENTRY_DT DATETIME,
BIRTH_DT DATETIME,
NAMES VARCHAR (25)
)
INSERT INTO TEMPS
VALUES ('123', '6/10/2015', '2/6/2018', 'JOHN'),
('123', '2/4/2018', '2/6/2018', 'SMITH'),
('123', '2/4/2018', '2/6/2018', 'DOE')它返回
ID Entry_Date Birth_Date Name
-----------------------------------
123 6/10/2015 2/6/2018 John
123 2/4/2018 2/6/2018 Smith
123 2/4/2018 2/6/2018 Doe我正在尝试查找Entry_Date列中日期离Birth_Date列更近(在3-6个月范围内)的记录。例如,在此临时表中,有2条记录的输入日期为2/4/18,接近出生日期2/6/18。以下是我尝试的两个步骤:
步骤1:
SELECT
id,
MIN(entry_dt) AS entry_dt
INTO
test
FROM
temps
GROUP BY
id第2步:
SELECT *
FROM temps a
INNER JOIN test b ON a.id = b.id
WHERE a.entry_dt > b.entry_dt比临时表更有效地提取更多记录的方法是什么?过滤离出生日期3-6个月的记录的最佳方法是什么?
发布于 2019-04-13 15:54:20
不需要使用insert data to test table。您可以在where子句中添加条件。
where birth_dt between entry_dt and dateadd(month,3,entry_dt)查询
select *
from TEMPS
where birth_dt between entry_dt and dateadd(month,3,entry_dt)输出

https://stackoverflow.com/questions/55656298
复制相似问题