2015-05-16 44 views
0

enter image description hereSql返回所有兄弟结果

我需要一些帮助来做一些查询。我会给出2个参数(@dateFrom,@dateTo)。基本上,tblRequesttblLog的关系是一对多的关系。我试图基于LogDate进行查询。假设我需要从2015/02/01 - 2015/02/28查询日期,我当前的查询将返回tblLog的一行结果。但是提到这个场景,取而代之的是返回1结果,我需要返回它的所有兄弟(同一个RequestId,这3行)。

select * from tblRequest 
inner join tblLog on tblLog.RequestId = tblRequest.Id 
where Logdate >= @dateFrom and Logdate < @dateto 

有人知道我该怎么做到这一点?我正在使用MS Sql。

+0

您正在使用哪个dbms? (看起来不像ANSI SQL,并且日期/时间功能通常是特定于产品的...) – jarlh

+0

由于您的日期范围,它只会返回一个结果,因为您在tbllog中只有1行具有此日期范围 – BrianAtkins

+0

是的,我意识到这一点。但我希望它返回所有的兄弟姐妹(即使条件不符合)。 – dausdashsan

回答

3

假设您的逻辑是正确的,那么您需要额外的join或条件来引入所有类似的请求ID。下面是使用in一个例子:

select r.name, l.* 
from tblRequest r inner join 
    tblLog l 
    on l.RequestId = r.Id 
where r.id in (select l2.RequestId 
       from tblLog l2 
       where l2.Logdate >= @dateFrom and l2.Logdate < @dateto 
      ); 

作为一个说明,你也可以用窗函数处理这个:

select rl.* 
from (select r.name, l.*, 
      sum(case when l.LogDate >= @dateFrom and l.Logdate < @dateto 
         then 1 else 0 
       end) over (partition by r.id) as cnt 
     from tblRequest r inner join 
      tblLog l 
      on l.RequestId = r.Id 
    ) rl 
where cnt > 0; 

两种不同的方式来完成同样的事情。

0

鉴于SQL的作品,你的上述方案将只返回1行,因为它是在该日期范围内唯一的一个,方式也许只是尝试:

select * from tblRequest 
inner join tblLog on tblLog.RequestId = tblRequest.Id 
where Logdate < @dateto 

这将返回所有结果为请求