在两个特定日期范围内过滤具有最大记录的SQL表

时间:2014-11-21 10:46:45

标签: sql

我想过滤一个表,首先按日期范围过滤,然后选择该指定时间段内的最大值记录。以下代码显示指定时间段内的记录。

所以在下面的例子中,我指定了1天,但它显示了2014-11-11的记录。

    declare @BgnDate date = '2014-11-10'
    declare @EndDate date ='2014-11-10'

    SELECT EmployeeName, TargetTxDate, sum(ActualTarget) as Actual, sum(RequiredTarget) AS ReqTarget, sum(variance) AS Variance 
    FROM dbo.TargetsTx as TargetsTx
    WHERE     (Variance IN
   (SELECT    MAX (Variance) AS Expr1
   FROM          dbo.TargetsTx AS TargetsTx_1
   WHERE      (@BgnDate IS NULL OR TargetsTx_1.TargetTxDate >= @BgnDate) AND
(@EndDate IS NULL OR TargetsTx_1.TargetTxDate < DATEADD(d, 1, @EndDate))))

  group by EmployeeName,TargetTxDate

2 个答案:

答案 0 :(得分:0)

你过度思考了吗?为什么不能这样:

SELECT EmployeeName, TargetTxDate, sum(ActualTarget) as Actual, sum(RequiredTarget) AS ReqTarget, sum(variance) AS Variance 
FROM dbo.TargetsTx as TargetsTx
WHERE TargetTxDate >= @BgnDate
AND TargetTxDate < @EndDate
group by EmployeeName,TargetTxDate
ORDER BY TargetTxDate DESC
LIMIT 1

答案 1 :(得分:0)

您的查询存在的问题是您在内部查询中有where。您可以通过将其放在外部查询中来修复它。但是,我建议使用window fucntions。

declare @BgnDate date = '2014-11-10'
declare @EndDate date ='2014-11-10'

SELECT e.*
FROM (SELECT t.*,
             ROW_NUMBER() OVER (PARTITION BY EmployeeName ORDER BY Variance DESC) as seqnum
      FROM dbo.TargetsTx t
      WHERE  (@BgnDate IS NULL OR TargetTxDate >= @BgnDate) AND
             (@EndDate IS NULL OR TargetsTx_1.TargetTxDate < DATEADD(d, 1, @EndDate)) 
     ) e
WHERE seqnum = 1;

我有点不清楚为什么你使用group by或你想要最大化的值(我猜variance),但这种技术适用于任何变量。