使用Microsoft SQL Server,我将连接两个表。表1中的一行可能与表2中的几行相关。理想情况下,我希望根据存在的数据和某些条件,从表2中返回一行
表2有一个连接在上的ID和一个datetime字段。我只带回日期时间为空的值,但是尽管它们是有效的,但如果日期时间仍然在将来,就不必要地将它们排除在外。
我希望能够从表2中带回一行,如果datetime字段在将来,该行优先于具有空值的行。如果将来没有具有datetime的联接行,它将返回空值row
我认为我需要某种形式的子查询,或者对当前行进行评分并返回最高值的东西,但我不确定。
无论使用哪种方法来完成此操作,在此查询中都有许多类似的情况,其中将使用此逻辑。
发布于 2014-05-26 17:59:18
如果我没记错的话,您希望从Table2中获取日期时间字段为空或将来有值的行。你说你希望将来的日期优先于空值,所以我理解你想要一个最大值。让我们设置一些示例数据:
CREATE TABLE Table1 (id_table1 int not null primary key)
INSERT INTO Table1 (id_table1)
VALUES (1)
INSERT INTO Table1 (id_table1)
VALUES (2)
INSERT INTO Table1 (id_table1)
VALUES (3)
INSERT INTO Table1 (id_table1)
VALUES (4)
INSERT INTO Table1 (id_table1)
VALUES (5)
CREATE TABLE Table2 (id_table2 int not null primary key, id_table1 int, date_value datetime)
INSERT INTO Table2 (id_table2,id_table1,date_value)
VALUES (1,1,'2001-01-01 00:00:00')
INSERT INTO Table2 (id_table2,id_table1,date_value)
VALUES (2,1,NULL)
INSERT INTO Table2 (id_table2,id_table1,date_value)
VALUES (3,1,'2015-01-01 00:00:00')
INSERT INTO Table2 (id_table2,id_table1,date_value)
VALUES (4,2, '2002-01-01 00:00:00')
INSERT INTO Table2 (id_table2,id_table1,date_value)
VALUES (5,3, '2003-01-01 00:00:00')
INSERT INTO Table2 (id_table2,id_table1,date_value)
VALUES (6,3, '2018-01-01 00:00:00')
INSERT INTO Table2 (id_table2,id_table1,date_value)
VALUES (7,4, '2004-01-01 00:00:00')
INSERT INTO Table2 (id_table2,id_table1,date_value)
VALUES (8,4,NULL)现在,每个id_table1在Table2中有0..n行。
首先,您可以从Table2获取匹配条件NULL或将来的所有行:
declare @datThreshold datetime
set @datThreshold=getdate()
SELECT *
FROM Table2 t2
WHERE t2.date_value is null OR t2.date_value>@datThreshold正如我所说的,我理解您想要剩余日期的最大值,其中NULL是最低值。您可以通过将空值设置为默认值来实现这一点,默认值可以是@datThreshold,因为根据WHERE条件,这将是最低值。
declare @datThreshold datetime
set @datThreshold=getdate()
SELECT id_table1, max(isnull(t2.date_value,@datThreshold)) max_date
FROM Table2 t2
WHERE t2.date_value is null OR t2.date_value>@datThreshold
GROUP BY t2.id_table1现在,每个id_table1都有一行,并且必须将其连接到Table1:
declare @datThreshold datetime
set @datThreshold=getdate()
SELECT t1.id_table1,max.id_table1,max.max_date
FROM Table1 t1
JOIN (SELECT id_table1, max(isnull(t2.date_value,@datThreshold)) max_date
FROM Table2 t2
WHERE t2.date_value is null OR t2.date_value>@datThreshold
GROUP BY t2.id_table1) max ON t1.id_table1=max.id_table1您也可以再次将默认日期替换为NULL:
declare @datThreshold datetime
set @datThreshold=getdate()
SELECT t1.id_table1,max.id_table1,case max.max_date when @datThreshold then NULL else max.max_date end date_value
FROM Table1 t1
JOIN (SELECT id_table1, max(isnull(t2.date_value,@datThreshold)) max_date
FROM Table2 t2
WHERE t2.date_value is null OR t2.date_value>@datThreshold
GROUP BY t2.id_table1) max ON t1.id_table1=max.id_table1https://stackoverflow.com/questions/23858889
复制相似问题