-1

在我的数据库中,我有一个小组可以在一周内活跃,开放时间。
A 组开始日期:22-10-2012 结束日期:28-10-2012(开始日期总是一周的开始)
A 组开始日期:29-10-2012 结束日期:04-11-2012(总是一周结束)

A组在这两周有两个不同的开放时间。

现在我有一个存储过程,它通过查看输入参数 StartDate 和 EndDate 返回活动组。如果这两个参数在一周的开始日期和结束日期之间,那么我得到了正确的开放时间。

但是当输入参数大约是两周(开始日期:22-10-2012 和结束日期:30-10-2012)时,我会得到两周的开放时间。

declare @Begindate datetime    
set @Begindate = '2012-10-22'

declare @Enddate datetime   
set @Enddate = '2012-11-02'


SELECT Id, Date, ..., ...   
FROM Table1 t1  
INNER JOIN Combinations c ON t1.Id=c.Table1Id
INNER JOIN Group g ON c.GroupId=g.Id  
WHERE t1.Date<= @Enddate) AND (t1.Date>= @Begindate  (gets dates I need)   
AND g.BeginDate <=@Enddate and g.Enddate >= @Begindate (Gets active groups)


Some table data:

Table1:

Id    Date         GroupId
1     2012-10-23   10
1     2012-10-29   10



Combinations: (holds the relation between Table1 and Group)

ID  Table1Id    GroupId
1   10          1


Group Table:

ID    Name     StartDate   EndDate     MondayOpen   MondayClose ...
1     Group A  2012-10-22  2012-10-28  08:00        18:00
1     Group A  2012-10-29  2012-11-04  13:00        18:00

通过这个查询,我得到了一个组两次,因为两个输入参数都超过了两周。

如何获得日期(从 t1 开始)查看组开始和结束日期的正确开放日期?

4

1 回答 1

1

您缺少 table1 和 [group] 之间的条件,这是下面查询中的最后一行。

SELECT *
FROM Table1 t1  
INNER JOIN Combinations c ON t1.Id=c.Table1Id
INNER JOIN [Group] g ON c.GroupId=g.Id  
WHERE t1.Date<= @Enddate AND t1.Date>= @Begindate 
AND g.BeginDate <=@Enddate and g.Enddate >= @Begindate
AND t1.Date between g.BeginDate and g.EndDate

SQLFiddle

于 2012-10-28T22:14:46.707 回答