来自联合的SQL总和

时间:2019-01-23 21:08:55

标签: sql sql-server sql-server-2012

我有2个表要合并在一起,我想对这些值求和,而不是使用具有相同ID的2个不同的行。这是我目前拥有的:

SELECT
    d.ID,
    SUM(d.balance) AS Balance
FROM  
    d
WHERE 
    d.status != 'closed'
GROUP BY 
    d.ID

UNION ALL

SELECT
    t.ID,
    SUM(t.balance) AS Balance
FROM 
    t
WHERE 
    t.status != 'closed'
GROUP BY 
    t.ID

这给了我一个包含所有d值,然后所有t值的列表,我希望所有具有匹配ID的行都在同一行

2 个答案:

答案 0 :(得分:3)

在当前查询周围放置一个外部查询,并按以下方式再次分组:

select id, sum(Balance)
from (
  SELECT d.ID, SUM(d.balance) AS Balance
  FROM d
  WHERE d.[status] != 'closed'
  GROUP BY d.ID

  UNION ALL

  SELECT t.ID, SUM(t.balance) AS Balance
  FROM t
  WHERE t.[status] != 'closed'
  GROUP BY t.ID
) X
group by id

实际上,实际上并不需要内部的group by,因此以下内容应该仍然有效并且更清楚:

select id, sum(Balance)
from (
  SELECT d.ID, d.balance
  FROM d
  WHERE d.[status] != 'closed'

  UNION ALL

  SELECT t.ID, t.balance
  FROM t
  WHERE t.[status] != 'closed'
) X
group by id

答案 1 :(得分:-1)

希望这对您有帮助

  DECLARE @DataSource TABLE
(
    [id] INT
   ,[Balance] Float
   ,status Varchar(50)

);

INSERT INTO @DataSource ([ID], [Balance],[Status])
VALUES (1, 100 ,'Closed')
      ,(2, 200,'Open' )
      ,(3, 300 ,'Onhold')
      ,(4, 400 ,'Open')


DECLARE @DataSource1 TABLE
(
   [id] INT
   ,[Balance] Float
  ,status Varchar(50)

);


INSERT INTO @DataSource1 ([ID], [Balance],[Status])
VALUES (1, 3 ,'Open')
      ,(2, 3 ,'Open')
      ,(3, 55 ,'Onhold')
      ,(4, 6 ,'Closed')


      SELECT d.ID,sum((Case When d.status!='Closed' Then d.Balance Else 0 End )+(Case When t.status!='Closed' Then t.Balance Else 0 End))
      FROM @DataSource d
     inner Join  @DataSource1 t
     on t.ID= d.ID
     Group By  d.ID,  t.ID


enter code here