SQL Server 2008 一列的总和值,每个值基于一个 table 的键值分为两个 table

SQL Server 2008 sum values of a column, each in two tables based on key values of one table

假设我有 2 个表:

T1 with composite keys DOC, VER, SN1
DOC  VER  SN1  NME  ISU
---  ---  ---  ---  ---
AP   03   5    COM  2
AP   03   4    COM  3
AP   03   3    ITC  2 
AP   02   4    PUR  10 
AP   02   2    PUR  5
AW   03   2    EXP  4
AW   03   1    COM  8
AW   01   1    QAS  3

T2 with composite keys DOC, VER, SN2
DOC  VER  SN2  NME  RET
---  ---  ---  ---  ---
AP   03   3    ITC  1
AP   03   2    COM  1
AP   03   1    COM  3 
AP   02   2    PUR  6 
AP   02   1    PUR  4
AW   01   1    QAS  3

结果集必须是:

DOC  VER  NME  TISU  TRET
---  ---  ---  ----  ----
AP   03   COM  5     4
AP   03   ITC  2     1
AP   02   PUR  15    10
AW   03   EXP  4     null
AW   03   COM  8     null 
AW   01   QAS  3     0

基本上,这总结了每个不同的 DOC、VER、NME 和 总结每个不同的 DOC、VER、NME 值的 RET 列。

我试过以下方法

select T1.DOC, T1.REV, T1.NME, SUM(T1.ISU) as TISU, 
       (select sum(T2.RET) from T2) as TRET
from T1
group by T1.DOC, T1.REV, T1.NME

这正确地总结了 TISU 列而不是 TRET 列,因为它重复了它在第一个总和中找到的值。

您可以将 where 添加到相关子查询中:

select T1.DOC, T1.REV, T1.NME, SUM(T1.ISU) as TISU, (
        select sum(T2.RET) 
        from T2 
        where T1.DOC = T2.DOC
          and T1.REV = T2.REV
          and T1.NME = T2.NME
          ) as TRET
from T1
group by T1.DOC, T1.REV, T1.NME

您还可以像这样加入执行聚合的子查询:

select T1.DOC, T1.REV, T1.NME, SUM(T1.ISU) as TISU, T2.TRET
from T1
  left join (
    select T2.DOC, T2.REV, T2.NME, SUM(T2.RET) as TRET
    from T2
    group by T2.DOC, T2.REV, T2.NME
  ) as T1
     on T1.DOC = T2.DOC
    and T1.REV = T2.REV
    and T1.NME = T2.NME 
group by T1.DOC, T1.REV, T1.NME, T2.TRET 

或者像这样加入两个子查询:

select T1.DOC, T1.REV, T1.NME, T1.TISU, T2.TRET
from (
    select T1.DOC, T1.REV, T1.NME, SUM(T1.ISU) as TISU
    from T1
    group by T1.DOC, T1.REV, T1.NME
  ) as T1
  left join (
    select T2.DOC, T2.REV, T2.NME, SUM(T2.RET) as TRET
    from T2
    group by T2.DOC, T2.REV, T2.NME
  ) as T1
     on T1.DOC = T2.DOC
    and T1.REV = T2.REV
    and T1.NME = T2.NME