2016-11-17 81 views
0

我只是試圖修改現有的查詢來在一週內添加(SUM)總小時數,如果數據超過40則將數據推送到表。我是新手到SQL,我不知道在這一點上如何實現這個公式。作爲一個方便的說明,我可以使用任何好的語法檢查程序來幫助?這是我必須修改的。特定日期之間的總和

SELECT dbo_Associates.FirstName 
    , dbo_Associates.LastName 
    , dbo_Events.DATE 
    , Sum(dbo_Events.Amount) AS SumOfAmount 
FROM (
    dbo_Events INNER JOIN dbo_Associates 
     ON dbo_Events.AssociateId = dbo_Associates.Id 
    ) 
INNER JOIN dbo_Categories 
    ON dbo_Events.CategoryId = dbo_Categories.Id 
WHERE (
     (
      (dbo_Categories.NAME) <> "Sub-Contractor" 
      AND (dbo_Categories.NAME) <> "Invoice" 
      AND (dbo_Categories.NAME) <> "Receipt" 
      AND (dbo_Categories.NAME) <> "Equipment" 
      AND (dbo_Categories.NAME) <> "Meetings" 
      AND (dbo_Categories.NAME) <> "Comp Time" 
      AND (dbo_Categories.NAME) <> "Training" 
      AND (dbo_Categories.NAME) <> "Other" 
      AND (dbo_Categories.NAME) <> "Overnight Stay (each)" 
      ) 
     ) 
GROUP BY dbo_Associates.FirstName 
    , dbo_Associates.LastName 
    , dbo_Events.DATE 
    , dbo_Associates.Id 
HAVING (
     (
      (dbo_Events.DATE) >= #8/31/2016 # 
      AND (dbo_Events.DATE) <= #9/15/2016 # 
      ) 
     AND ((Sum(dbo_Events.Amount)) >= 11.25) 
     AND (
      (dbo_Associates.Id) <> 17 
      AND (dbo_Associates.Id) <> 40 
      AND (dbo_Associates.Id) <> 41 
      AND (dbo_Associates.Id) <> 44 
      AND (dbo_Associates.Id) <> 45 
      AND (dbo_Associates.Id) <> 47 
      ) 
     ) 
ORDER BY dbo_Associates.FirstName; 
+2

我強烈懷疑這是比您需要提供的更多*更復雜的查詢來演示此問題。請簡化它,以便它*只處理您遇到的問題。 –

+1

你正在使用什麼數據庫? – randominstanceOfLivingThing

回答

0

不管所有其他的東西你的查詢是幹什麼的,你需要做的就是計算sum(Amount)在內部查詢,而不是外部查詢什麼。該結構將是:

SELECT a.group_var, a.tot_amount, [other variables you need] 
FROM 
    (SELECT group_var, sum(amount) as tot_amount 
     FROM sourcetbl 
    GROUP BY group_var) as a 
INNER JOIN othertbl as b 
    ON a.group_var = b.group_var 
WHERE tot_amount > 40 
    and [whatever] = [whatever value] 

這是因爲你不能使用WHERE你在同一個查詢正在做一個計算標準,所以你必須有已經可以在何地使用計算的總和。您可以包含所需的許多聯接和WHERE條件,但請記住,無論它們引用哪個表,最後所有WHERE條件都會結束。