答案 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