简化T-SQL查询

时间:2014-03-06 11:47:32

标签: sql-server tsql optimization

如果可能,我想简化此查询。

SELECT 
    MAX(tDateTimeOfSurvey) 
FROM 
    Stocks.dbo.tblSurvey
WHERE
    (   
       (SELECT ISNULL(SUM(tWetTons), 0) 
        FROM Stocks.dbo.tblSurvey 
        WHERE tStockAreaID = 3
          AND tDateTimeOfSurvey BETWEEN '20140201' AND '20140228') + 
      (SELECT ISNULL(SUM(tWetTons), 0) 
       FROM Stocks.dbo.tblSurvey 
       WHERE tStockAreaID = 103
         AND tDateTimeOfSurvey BETWEEN '20140201' AND '20140228') + 
      (SELECT ISNULL(SUM(tWetTons), 0) 
       FROM Stocks.dbo.tblSurvey 
       WHERE tStockAreaID = 181
         AND tDateTimeOfSurvey BETWEEN '20140201' AND '20140228')
    ) > 0
AND tStockAreaID IN (3,103,181) -- RAS, SOIL, DORB
AND tDateTimeOfSurvey BETWEEN '20140201' AND '20140228' 

非常感谢,皮埃尔

1 个答案:

答案 0 :(得分:1)

请尝试:

SELECT MAX(tDateTimeOfSurvey) 
FROM Stocks.dbo.tblSurvey 
WHERE
    tStockAreaID IN (3,103,181) AND 
    tDateTimeOfSurvey BETWEEN '20140201' AND '20140228' 
HAVING SUM(tWetTons)>0