2014-11-21 60 views
0

我想過濾一個表,首先按日期範圍,然後在該指定的時間段內選擇最大值記錄。下面的代碼顯示超出指定時間段的記錄。在兩個特定日期範圍內過濾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 
+1

你正在研究哪個dbms? MySQL的? MSSQL?甲骨文? ..... – Fred 2014-11-21 11:14:30

回答

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 
+0

我想我已經過時了,感謝 – user3656185 2014-11-24 06:41:20

0

您的查詢的問題是,您在內部查詢中有where。您可以通過將其放入外部查詢來修復它。不過,我會推薦使用窗口函數。

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),但這種技術可以在任何的變量。

+0

收到謝謝,這也很有效,謝謝你的勸告。 – user3656185 2014-11-24 06:42:15

相關問題