使用三个表中的数据更新查询

时间:2016-07-01 08:25:19

标签: sql-server

我有三张桌子,familycall表是这样的:
enter image description here

CDR表是这样的:

enter image description here


FamilyCallDetail是这样的:

enter image description here


我想写这个更新查询:

update FamilyCallDetail
where familyCallDetail.Anumber=under select query anumber
set duration=duration+(
    select anumber,sum(duration)
    where familyCall.anumber=Cdr.Anumber and FamilyCall.Bnumber=Cdr.Bnumber

)


如何编写更新查询?感谢每一个。

2 个答案:

答案 0 :(得分:2)

我认为这就是你要做的事情:

;
WITH CTE_Aggregate AS (
  SELECT
    fc.Anumber,
    SUM(cdr.Duration) AS Duration
  FROM FamilyCall AS fc
  INNER JOIN CDR AS cdr
    ON cdr.Anumber = fc.Anumber
    AND cdr.Bnumber = fc.Bnumber
  GROUP BY fc.Anumber
)
UPDATE fcd
SET fcd.Duration = fcd.Duration + cte.Duration
FROM FamilyCallDetail fcd
INNER JOIN CTE_Aggregate AS cte
  ON cte.Anumber = fcd.Anumber;

答案 1 :(得分:1)

很难说你真正想做什么。可能这个?

update FamilyCallDetail
where familyCallDetail.Anumber = IN (select query anumber)
set duration = duration + (
    select sum(duration)
    FROM Cdr 
        innner join FamilyCall on (
          Crd.Anumber = FamilyCall.Anumber 
          and Cdr.Bnumber = FamiliyCall.Bnumber)
    where familyCall.anumber=FamilyCallDetail.Anumber
)

它将所有Cdr的持续时间添加到FamiliyCallDetail,它具有相同的Anumber,并且在FamilyCall中有一个由Anumber和Bnumber链接的条目。我不确定Bnumber和FamilyCall是否真的相关。如果没有,它会变得更简单。