SQL Server 2008总和列的值,每个列在两个表中,基于一个表

时间:2017-03-21 13:00:10

标签: sql-server-2008 aggregates

说我有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和的ISU列 总结每个不同的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列,因为它重复了它在第一个总和处找到的值。

1 个答案:

答案 0 :(得分:0)

您可以在相关子查询中添加ifstream fin("file.in"); int k; cin >> k; queue<string> Q; string line; for(; getline(fin, line); ){ if(Q.size() == k){ Q.pop(); } Q.push(line); } while(!Q.empty()){ cout << Q.front() << endl; Q.pop(); }

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