SQL SELECT 来自 TABLE 的数据,其中 NUMBER 存在于另一个 TABLE 日期范围内

SQL SELECT data from TABLE where NUMBER EXISTS in another TABLE in date range

我有两张桌子。我想 select 全部来自 TABLE1 其中 ID 存在于 TABLE 2 并且具有当前日历年中任何一天的 DATE

TABLE 1

TABLE 2

期望的结果

你可以使用WHERE EXISTS喜欢

select * from table1 t
where exists (select 1 from table2
where ID = t.ID and year([DATE]) = year(getdate());

正如@GarethD 指出的那样,在不使用 if YEAR() 函数的情况下修改了 WHERE,该函数将使用索引(如果该列上有索引)

SELECT * FROM table1 t
WHERE EXISTS (SELECT 1 FROM table2
WHERE ID = t.ID 
AND [Date] >= DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0) 
AND [Date] <  DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) + 1, 0));

这是您的解决方案

CREATE TABLE #Table1 
(
ID int
,NAME varchar(50)
,Description varchar(250)
)
INSERT INTO #Table1 (ID,NAME,Description)
VALUES (1,'One','The First Item'),
(2,'Two','The second item'),
(3,'Three','The third item'),
(4,'Four','The fourth item'),
(5,'Five','The fith item'),
(6,'Six','The sixth item'),
(7,'Seven','The seventh item'),
(8,'Eight','The eight item'),
(9,'Nine','The ninth item');

CREATE TABLE #Table2
(
ID int
,Date date
)
INSERT INTO #Table2 (ID,Date)
VALUES (1,'1/15/2015'),
(1,'8/8/2015'),
(2,'9/23/2014'),
(3,'7/19/2015'),
(4,'4/23/2010'),
(4,'6/30/2009'),
(4,'12/25/2014'),
(5,'5/17/2015'),
(6,'12/3/2008'),
(9,'9/25/2009'),
(9,'2/2/2015'),
(9,'1/31/2012')
;


SELECT
*
FROM #Table1 t
WHERE t.ID IN (SELECT t2.ID FROM #Table2 t2 WHERE DATEPART(YEAR,t2.Date) = DATEPART(YEAR,GETDATE()))

DROP TABLE #Table1
DROP TABLE #Table2