我有这个问题与查询这两个表之间没有任何链接,我试图结合。表1的有效期和到期日必须与PollDate的表2相关联。 PollDate不得介于有效期和失效期之间。
Table 1
ClientID EffectiveDate ExpirationDate
1 2009-04-01 00:00:00.000 2009-12-18 00:00:00.000
1 2010-02-12 00:00:00.000 2010-03-05 00:00:00.000
1 2010-05-18 00:00:00.000 NULL
1 2009-12-21 00:00:00.000 2010-02-08 00:00:00.000
1 2010-12-19 00:00:00.000 2009-12-20 00:00:00.000
Table 2
ClientID PollDate
1 2009-12-20 00:00:00.000
1 2009-12-19 00:00:00.000
1 2010-02-12 00:00:00.000
1 2010-02-27 00:00:00.000
1 2010-05-19 00:00:00.000
1 2010-05-29 00:00:00.000
1 2010-05-30 00:00:00.000
1 2010-05-31 00:00:00.000
1 2010-06-05 00:00:00.000
1 2010-06-25 00:00:00.000
1 2010-06-27 00:00:00.000
1 2010-07-02 00:00:00.000
1 2010-08-04 00:00:00.000
1 2010-08-20 00:00:00.000
Result
ClientID inValidDate
1 2009-12-20 00:00:00.000
1 2009-12-19 00:00:00.000
答案 0 :(得分:0)
不确定语法,但你想做这样的事情。
select clientID, polDate as 'inValidDate'
FROM Table1 t1
INNER JOIN Table2 t2
ON t2.PolDate not in between t1.EffectiveDate and t1.ExpirationDate
编辑: 假设到期日期为空,则表示策略永不过期。
select clientID, polDate as 'inValidDate'
FROM Table1 t1
INNER JOIN Table2 t2
ON t2.PolDate not in between t1.EffectiveDate and ISNULL(t1.ExpirationDate, '2999-01-01')
答案 1 :(得分:0)
select t2.ClientID, t2.PoolDate
from Table1 t1, Table2 t2
where t2.PollDate between t1.EffectiveDate and t1.ExpirationDate
因为你没有加入连接条件,table1的每一行都会与table2的每一行匹配
答案 2 :(得分:0)
以下是@ AJP结果的略微变化 - 只考虑ExpirationDate
中的NULL值:
CREATE TABLE #Table1
(
[ClientID] INT,
[EffectiveDate] DATETIME,
[ExpirationDate] DATETIME
)
INSERT INTO #Table1
(
[ClientID],
[EffectiveDate],
[ExpirationDate]
)
SELECT 1, '2009-04-01', '2009-12-18' UNION
SELECT 1, '2010-02-12', '2010-03-05' UNION
SELECT 1, '2010-05-18', NULL UNION
SELECT 1, '2009-12-21', '2010-02-08' UNION
SELECT 1, '2010-12-19', '2009-12-20'
CREATE TABLE #Table2
(
[ClientID] INT,
[PollDate] DATETIME
)
INSERT INTO #Table2
(
[ClientID],
[PollDate]
)
SELECT 1, '2009-12-20' UNION
SELECT 1, '2009-12-19' UNION
SELECT 1, '2010-02-12' UNION
SELECT 1, '2010-02-27' UNION
SELECT 1, '2010-05-19' UNION
SELECT 1, '2010-05-29' UNION
SELECT 1, '2010-05-30' UNION
SELECT 1, '2010-05-31' UNION
SELECT 1, '2010-06-05' UNION
SELECT 1, '2010-06-25' UNION
SELECT 1, '2010-06-27' UNION
SELECT 1, '2010-07-02' UNION
SELECT 1, '2010-08-04' UNION
SELECT 1, '2010-08-20'
SELECT
t2.[ClientID],
t2.[PollDate] AS 'inValidDate'
FROM
#Table1 AS t1
JOIN
#Table2 AS t2
ON
(t2.[PollDate] < t1.[EffectiveDate]
OR t2.[PollDate] > ISNULL(t1.[ExpirationDate], '9999-12-31'))
AND t1.ClientID = t2.ClientID -- Not clear from your question if this is necessary