按日期在另一个表中筛选查询

时间:2016-01-16 16:08:42

标签: sql ms-access

每个月我都需要过滤观看日期以获取季度数据。在其他查询中,我已经看到使用具有开始日期和结束日期的表,用户可以在WHERE子句中引用其他视图可以引用的表,从而无需手动更改日期。我不确定这是否会导致性能问题,或者它是否是一种效率低下的方法。无论哪种方式,对于具有外连接的查询,此方法不起作用。下面是产生错误的代码示例(不是我正在使用的实际表或代码,但是同样的问题):

SELECT performer.firstname, 
       performer.lastname, 
       Sum(score.points) AS SumOfPoints 
FROM   rundates, 
       (performer 
        LEFT JOIN score 
               ON performer.performerid = score.performerid) 
       INNER JOIN show 
               ON ( show.performerid = score.performerid ) 
                  AND ( show.episodenumber = score.episodenumber ) 
                  AND ( show.seasonnumber = score.seasonnumber ) 
                  AND ( performer.performerid = show.performerid ) 
WHERE  (( ( show.airdate ) BETWEEN [rundates].[begindate] AND 
                                   [rundates].[enddate] )) 
GROUP  BY performer.firstname, 
          performer.lastname; 

问题:

  1. 除了将上述内容转换为子查询之外,还有办法进行过滤 然后在子查询上执行WHERE子句?
  2. 是否有一种标准方法可以按日期范围过滤多个视图,除了更改每个可以应用于除上述表格方法之外的所有查询的BETWEEN标准之外?
  3. 表格方法编写的代码是否会导致以后出现问题?

1 个答案:

答案 0 :(得分:0)

WITH 
SELECT DATEADD(month, DATEDIFF(month, -3, @mydate), 0) AS StartOfThreeMonthsBack,
       DATEADD(month, DATEDIFF(month, 0, @mydate), 0) AS StartOfCurrentMonth 
AS BOUNDARIES

SELECT <your select>
FROM <your table>, BOUNDARIES
WHERE...
  AND <date from your field> >= BOUNDARIES.StartOfThreeMonthsBack
  AND <date from your field> <  BOUNDARIES.StartOfCurrentMonth 

很抱歉没有工具可以测试它,但这是个主意