获取子表中当前日期没有行的所有父行?

时间:2014-02-18 07:30:07

标签: sql-server tsql sql-server-2005

SELECT 
    [dbo].[Mission].[MissionId]  
FROM 
    [dbo].[Mission] 
LEFT OUTER JOIN 
    [dbo].[Report] ON [dbo].[Mission].[MissionId] = [dbo].[Report].[MissionId] 
WHERE 
    [dbo].[Report].ReportDate IS NULL 
ORDER BY 
    [dbo].[Mission].[MissionId]

如何更改上述查询,以便它为表格MissionId中的所有[dbo].[Mission]提供表[dbo].[Report]中没有行的[dbo].[Report].ReportDate今天?

MissionId是表Mission中的主键和表Report中的外键。所以我希望得到当前日期表Report中没有一行的所有任务。

2 个答案:

答案 0 :(得分:4)

我已经引入了一些别名来使查询更容易阅读,并添加了所需的条件。我也改变了WHERE条款,不确定是否需要:

SELECT m.[MissionId]  
FROM [dbo].[Mission] m LEFT OUTER JOIN [dbo].[Report] r
  ON m.[MissionId] = r.[MissionId] 
  AND r.ReportDate = DATEADD(day,DATEDIFF(day,0,GETDATE()),0)
WHERE r.MissionId IS NULL 
ORDER BY m.[MissionId]

这假定ReportDate包含时间部分设置为午夜的日期。如果不是这样,则需要稍微复杂的查询:

SELECT m.[MissionId]  
FROM [dbo].[Mission] m 
WHERE NOT EXISTS(select * from dbo.Report r
                where r.MissionID = m.MissionID and
                   r.ReportDate >= DATEADD(day,DATEDIFF(day,0,GETDATE()),0) and
                   r.ReportDate < DATEADD(day,DATEDIFF(day,0,GETDATE()),1)
                )
ORDER BY m.[MissionId]

GETDATE()返回当前日期和时间。我正在使用DATEADDDATEDIFF的几个技巧来获取该值,并将其转换为午夜的当前日期,以及(在第二个查询中)明天的午夜日期。


第二个查询作为完全可运行的查询:

declare @mission table (MissionID int not null);
insert into @mission (MissionID) select 1 union all select 2;
declare @report table (MissionID int not null,ReportDate datetime not null);
insert into @report (MissionID,ReportDate)
select 2,GETDATE() union all select 1,DATEADD(day,-1,GETDATE());

SELECT m.[MissionId]  
FROM @mission m 
WHERE NOT EXISTS(select * from @report r
                where r.MissionID = m.MissionID and
                   r.ReportDate >= DATEADD(day,DATEDIFF(day,0,GETDATE()),0) and
                   r.ReportDate < DATEADD(day,DATEDIFF(day,0,GETDATE()),1)
                )
ORDER BY m.[MissionId]

结果:

MissionId
-----------
1

答案 1 :(得分:0)

select
  m.MissionId
from Mission m 
left join Report r
  on  m.MissionId = r.MissionId
  and day(r.ReportDate) = day(getdate())
  and month(r.ReportDate) = month(getdate())
  and year(r.ReportDate) = year(getdate())
WHERE r.ReportDate is null
ORDER BY m.MissionId