求总和

Finding Total of Sum

我写了这个查询来查找 Net 的总和。但是我收到一个错误。你们能帮帮我吗?

SELECT SUM(net) AS net
FROM (select SUM(FB.[Net]) as net  FROM  (([table1 AS FB INNER JOIN
Date ON FB.DateKey =  Date.DateKey)
inner join [Store] on [Store].StoreKey = FB.StoreKey) WHERE (FullDate BETWEEN DATEADD(WEEK, -12, CONVERT(date, GETDATE())) 
AND DATEADD(day, -1, CONVERT(date, GETDATE()))
AND SName = 'XYZ'
AND DayNameOfWeek = 'Monday')
GROUP BY FB.[Net])

亲切的问候

格式化代码是关键:

SELECT  SUM(net) AS net
FROM    (
            SELECT  SUM(FB.[Net]) as net  
            FROM    ((
                        [table1 AS FB 
                        INNER JOIN  Date 
                                ON  FB.DateKey =  Date.DateKey
                    )
                    inner join [Store] 
                            on [Store].StoreKey = FB.StoreKey
                    ) 
                    WHERE   (FullDate BETWEEN DATEADD(WEEK, -12, CONVERT(date, GETDATE())) 
                        AND DATEADD(day, -1, CONVERT(date, GETDATE()))
                        AND SName = 'XYZ'
                        AND DayNameOfWeek = 'Monday')
                    GROUP BY FB.[Net]
                    )

我现在可以看到很多错误。我认为这解决了大多数语法错误,但我不确定它是否提供了您想要的结果:

SELECT  SUM(net) AS net
FROM    (
            SELECT  SUM([Net]) as net  
            FROM    (
                        SELECT      FB.net
                        FROM        table1 AS FB 
                        INNER JOIN  [Date] 
                                ON  FB.DateKey =  [Date].DateKey                    
                        inner join  [Store] 
                                on  [Store].StoreKey = FB.StoreKey                  
                        WHERE   FullDate BETWEEN DATEADD(WEEK, -12, GETDATE()) AND DATEADD(day, -1, GETDATE())
                            AND SName = 'XYZ'
                            AND DayNameOfWeek = 'Monday'
                        GROUP BY FB.[Net]
                    ) A
        ) B

edit 这是您自己的代码,没有语法错误(据我所知)。下面的代码应该给出相同的结果集:

SELECT      SUM(DISTINCT FB.net)
FROM        table1 AS FB 
INNER JOIN  [Date] 
        ON  FB.DateKey =  [Date].DateKey                    
INNER JOIN  [Store] 
        ON  [Store].StoreKey = FB.StoreKey                  
WHERE       FullDate BETWEEN DATEADD(WEEK, -12, GETDATE()) AND DATEADD(day, -1, GETDATE())
        AND SName = 'XYZ'
        AND DayNameOfWeek = 'Monday'

你确定这是你想要的吗?

像这样尝试,删除不必要的括号并添加适当的别名。请同时将别名添加到 "Where" 子句过滤器。

SELECT SUM(net) AS net
FROM (
    SELECT SUM(FB.[Net]) AS net
    FROM [table1] FB
    INNER JOIN [Date] D ON FB.DateKey = D.DateKey
    INNER JOIN [Store] S ON S.StoreKey = FB.StoreKey
    WHERE FullDate BETWEEN DATEADD(WEEK, - 12, CONVERT(DATE, GETDATE()))
            AND DATEADD(day, - 1, CONVERT(DATE, GETDATE()))
        AND SName = 'XYZ'
        AND DayNameOfWeek = 'Monday'
    GROUP BY FB.[Net]
    ) t