Sql返回所有兄弟结果

时间:2015-05-16 13:44:13

标签: sql sql-server

enter image description here

我需要一些帮助才能进行一些查询。我将获得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。

2 个答案:

答案 0 :(得分: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;

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

答案 1 :(得分:0)

考虑到SQL的工作方式,上面的场景只会返回1行,因为它是该日期范围内的唯一行,可能只是尝试:

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

这将返回该请求的所有结果