0

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

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 的列。我想知道最好的方法是什么。我可以将它添加到存储过程中并将变量添加到每个选择查询中。或者有没有更好的方法在日期范围内运行查询。

4

2 回答 2

1

i think just add an additional where clause item similar to:

AND ( rDate > somedate AND rDate < someotherdate )
于 2013-01-07T21:28:36.020 回答
0

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

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

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

虽然我没有任何数据要测试,但您可能会考虑以下查询,因为它更易于阅读并且性能可能更好。但是你必须自己检查结果,也许做一些调整。

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
于 2013-01-07T21:31:52.313 回答