具有日期范围的多选sql查询

时间:2013-01-07 21:15:49

标签: sql

我有这个查询,我从员工名单表中获得不同统计数据的总数。

SELECT A.rempid AS EmpId, 
       E.flname, 
       A.rdo_total, 
       B.grave_total, 
       C.sundays, 
       D.holidays 
FROM   (SELECT rempid, 
               Count(rshiftid)AS RDO_Total 
        FROM   rtmp1 
        WHERE  rshiftid = 2 
        GROUP  BY rempid 
        HAVING Count(rshiftid) > 0) A, 
       (SELECT rempid, 
               Count(rshiftid)AS Grave_Total 
        FROM   rtmp1 
        WHERE  rshiftid = 6 
        GROUP  BY rempid 
        HAVING Count(rshiftid) > 0)B, 
       (SELECT rempid, 
               Count(rshiftid) AS Sundays 
        FROM   rtmp1 
        WHERE  Datepart(dw, rdate) = 1 
               AND rshiftid > 2 
        GROUP  BY rempid 
        HAVING Count(rshiftid) > 0)C, 
       (SELECT rempid, 
               Count(rshiftid) AS Holidays 
        FROM   rtmp1 
        WHERE  rdate IN (SELECT pubhdt 
                         FROM   pubhol) 
               AND rshiftid > 2 
        GROUP  BY rempid 
        HAVING Count(rshiftid) > 0)D, 
       (SELECT empid, 
               [fname] + ' ' + [sname] AS flName 
        FROM   remp1)E 
WHERE  A.rempid = B.rempid 
       AND A.rempid = E.empid 
       AND A.rempid = C.rempid 
       AND A.rempid = D.rempid 
ORDER  BY A.rempid 

我想在其中添加日期范围,以便我可以在2个日期内查询数据库。 rTmp1表有一个名为rDate的列。我想知道最好的方法是什么。我可以将它添加到存储过程并向每个选择查询添加变量。或者是否有更好的方法在日期范围内运行查询。

2 个答案:

答案 0 :(得分:1)

我认为只需添加一个类似于:

的附加where子句项
AND ( rDate > somedate AND rDate < someotherdate )

答案 1 :(得分:0)

为每个查询添加日期范围是最直接的解决方案。

使其成为存储过程总是可以通过查询完成,但与此特定情况无关。

如果将表缩小到指定日期范围所产生的记录数远远少于整个表,则可以选择将这些记录插入a temporary table or a table variable并在该表上运行现有查询/结果集。

虽然我没有要测试的数据,但您可能会考虑以下查询,因为它更容易阅读并且可能表现更好。但你必须亲自检查一下结果,并做一些调整。

DECLARE @startDate date = '12/01/2012'
DECLARE @endDate date = DATEADD(MONTH, 1, @startDate)

SELECT
  [e].[empid],
  [e].[fname] + ' ' + [e].[sname] AS [flName],
  SUM(CASE WHEN [t].[rshiftid] = 2 THEN 1 ELSE 0 END) AS [RDO_Total],
  SUM(CASE WHEN [t].[rshiftid] = 6 THEN 1 ELSE 0 END) AS [Grave_Total],
  SUM(CASE WHEN [t].[rshiftid] > 2 AND DATEPART(dw, [t].[rdate]) = 1 THEN 1 ELSE 0 END) AS [Sundays],
  SUM(CASE WHEN [t].[rshiftid] > 2 AND [h].[pubhdt] IS NOT NULL THEN 1 ELSE 0 END) AS [Holidays]
FROM [remp1] [e]
INNER JOIN [rtmp1] [t] ON [e].[empid] = [t].[rempid]
LEFT JOIN [pubhol] [h] ON [t].[rdate] = [h].[pubhdt]
WHERE [t].[rdate] BETWEEN @startDate AND @endDate
GROUP BY 
  [e].[empid],
  [e].[fname],
  [e].[sname]
ORDER BY [empid] ASC