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

时间:2015-09-24 14:40:34

标签: tsql sql-server-2008-r2 exists

我有两张桌子。我想从 TABLE1 中选择全部,其中 ID 存在于 TABLE2 中并且当前任何一天都有 DATE 公历年。

表1

enter image description here

表2

enter image description here

期望的结果

enter image description here

2 个答案:

答案 0 :(得分:2)

您可以使用>>> def a(): ... localb = 10 ... def c(): ... print(locals()) ... print(eval('localb + 20')) ... c() ... >>> a() {} Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 7, in a File "<stdin>", line 5, in c File "<string>", line 1, in <module> NameError: name 'localb' is not defined 之类的

WHERE EXISTS

正如@GarethD指出的那样,如果select * from table1 t where exists (select 1 from table2 where ID = t.ID and year([DATE]) = year(getdate()); 函数将使用索引(如果该列上有任何内容),则不使用WHERE进行修改

YEAR()

答案 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