2014-01-22 66 views
-1

问题是当我尝试从2个不同的表中获得总和值,但是使用表3中的条件结果被错误的总和结果损坏。所以,我想Select sum() as t1 (select sum()...)t2,我想总结t1t2,这样t1t2结果正确 所以有代码SQL SERVER SELECT总和值

SELECT 
    SUM(daa.[price]) AS t1, 
    (
     SELECT SUM(dap.[price]) AS suma 
     FROM fydtr.dbo.[sales] AS dap, 
      [fydtr].[dbo].[work info] AS di 
     WHERE YEAR(di.[end of work datetime]) = 2013 
      AND MONTH(di.[end of work datetime]) = 12 
      AND di.[state] = 'e' 
      AND di.[reg. nr.] = dap.[reg. nr.] 
) AS t2 
FROM [fydtr].[dbo].[work sale] AS daa, 
    fydtr.dbo.[work info] AS dbi 
WHERE YEAR(dbi.[end of work datetime]) = 2013 
    AND MONTH(dbi.[end of work datetime]) = 12 
    AND dbi.[state] = 'e' 
    AND dbi.[reg. nr.] = daa.[reg. nr.] 

它给结果

T1 340
T2 509

而我需要总结这些并得到849作为t3。

+7

[为什么] [有] [你] [使用] [方形] [括号] [无处不在],[当] [你] [不]需要]? – Bohemian

+0

[when] [when] [you] [save] [the] [tables] [path] [you] [can] [save] [script] [file] [and] [open] [for] [编辑] [没有] [错误] [该表无法找到] – miskovelnias

+1

那么,什么?可读性胜过便利。如果问题存在,请向脚本添加一些更改为正确数据库的脚本。不要用不必要的字符污染代码,如果没有被破坏,不要修复它。顺便说一下,我会立即解雇任何在列/表名中放置空格的人。 – Bohemian

回答

1

这样的事情呢。

select t1, t2, t1 + t2 t3 
from (
the query from your question 
) temp 
0

由于缺少输入数据,不完全清楚。但我认为你正在寻找这样的东西:

select sum(sale.pice) as t1 
    , sum(sales.price) as t2 
    , sum(sales.price) + sum(sale.price) as t3 
    from [work info] as info 
     left outer join [work sale] as sale on (info.state = 'e' and info.[reg. nr.] = sale.[reg. nr.]) 
     left outer join [work sales] as sales on (info.state = 'e' and info.[reg. nr.] = sales.[reg. nr.]) 
    where year(info.[end of work datetime]) = 2013 
     and month(info.[end of work datetime]) = 12 

这取决于你的表之间的关系,例如,在我的例子中,我假设每个[reg。只有一个条目。在所有表格中。否则,您可以使用“窗口功能”或UNION或CTE(http://msdn.microsoft.com/en-us/library/ms175972.aspx)。您可能需要提供更多的上下文才能获得您要搜索的答案。

我给出的查询可能比您的查询有点干净。如果这不是问题,或者我的假设是错误的,Dan Bracuk的答案可以帮助你。

你也应该看看列名。他们有点太复杂,我认为:)