SQL SERVER SELECT和值

时间:2014-01-22 12:55:55

标签: sql sql-server tsql

问题是当我尝试从2个不同的表中获取总和值时,但使用表3中的条件结果会被错误的求和结果破坏。所以我尝试Select sum() as t1 (select sum()...)作为t2,我希望总结t1t2,这样t1t2结果是正确的 所以有代码

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。

2 个答案:

答案 0 :(得分:1)

这样的事情怎么样。

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

答案 1 :(得分: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。 nr。]在所有表格中。否则你可以使用“窗口函数”,或UNIONS或CTE(http://msdn.microsoft.com/en-us/library/ms175972.aspx)。您可能需要提供更多上下文才能获得您正在搜索的答案。

我的给定查询可能比您的查询更清晰。如果这不是问题,或者我的假设是错误的,那么Dan Bracuk的回答可以帮助你。

你也应该看一下列名。在我看来,它们有点太复杂了。)