特定日期之间的总和

时间:2016-11-17 17:59:50

标签: sql

我只是想修改一个现有的查询,以便在一周内添加(SUM)总小时数,然后将数据推送到表中,如果它们超过40岁。我是SQL和I的新手目前还不知道如何实施这个公式。作为旁注,我可以使用任何好的Syntax检查器来帮助吗?这是我必须修改的。

 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;

1 个答案:

答案 0 :(得分: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条件,但请记住,无论它们引用哪个表,所有WHERE条件都会结束。