加入"不等于"的SUM值线

时间:2018-04-26 15:26:33

标签: sql sql-server join sum left-join

我需要加入两个表,如下所示:

enter image description here

简单地说,我需要找到Table2中行的SUM值,其中POLE值不等于Table1中的值。什么样的查询可以起作用?

您可以下载电子表格from this link.

3 个答案:

答案 0 :(得分:1)

select t1.Pole, t1.Org, t1.Item, t1.OH, t1.[MAX],
(select sum(OH) from table2 t2 where t2.Pole <> t1.Pole) as [OH in other poles],
(select sum([MAX]) from table2 t2 where t2.Pole <> t1.Pole) as [MAX in other poles]
from table1 t1;

答案 1 :(得分:1)

select *
from table1 t
    cross apply (
        select sum(t2.oh) as oh_oth, sum(t2."max") as max_oth
        from table2 t2
        where t2.pole <> t.pole
    ) oth

答案 2 :(得分:0)

Cetin's answer会返回您预期的答案集,但将两个标量子查询合并为一个可能更有效:

WITH cte AS 
 ( -- calculate both MAX & SUM using a Cross Join
   SELECT t1.pole
      ,Sum(t2.oh) AS otherSum
      ,Max(t2.[Max]) AS otherMax
   FROM table2 AS t2 CROSS JOIN table2 AS t1
   WHERE t2.Pole <> t1.Pole
   GROUP BY t1.pole
 )
SELECT t1.*, cte.otherSum, cte.otherMax
FROM table1 AS t1
LEFT JOIN cte -- can be an Inner Join if all POLEs exist in both tables 
  ON t1.pole = cte.pole