连接2个表(即使它们具有空值)并加总每一行

时间:2019-04-16 19:05:26

标签: sql-server-2012

请参阅下面的图片,了解我想如何使用sql语句。我使用了左联接和ISNULL来获得所有结果,但我没有得到总数,我想对每个客户的数字求和。表b的所有值都是整数。

Select a.CustomerId, a.FName, a.LName, b.mtg1, b.mtg2, b.mtg3, b.mtg4 From Customer a Left Join Hours b On a.CustomerID = b.CustomerID group by a.Lname

enter image description here

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:1)

GROUP BY将使得捕获所有必要的数据变得有些困难。另外,不同列的总和将需要使用COALESCE(column, 0) so as to use zero as the value if the column is null because if not done, your total will come back as NULL`。

一个可能的解决方案是:

SELECT a.CustId, a.FName, a.LName, SUM(b.mtg1), SUM(b.mtg2), SUM(b.mtg3), SUM(b.mtg4), (COALESCE(SUM(b.mtg1), 0) + COALESCE(SUM(b.mtg2), 0) + COALESCE(SUM(b.mtg3), 0) + COALESCE(SUM(b.mtg4), 0)) AS total
FROM table_a a
LEFT JOIN table_b b ON(b.CustID = a.CustId)
GROUP BY a.CustID, a.FName, a.LName

答案 1 :(得分:0)

 with cte as
 (
 select flname+', '+fname as Name,
        mtg1,mtg2,mtg3,mtg4,
        isnull(((case when mtg1 is null then 0 else mtg1 end)+
                (case when mtg2 is null then 0 else mtg2 end)+
                (case when mtg3 is null then 0 else mtg3 end)+
                (case when mtg4 is null then 0 else mtg4 end)),0) as total

   from a left join b
   on   a.custid = b.custid

   )
   select name,
          isnull(mtg1,0) as mtg1,
          isnull(mtg2,0) as mtg2,
          isnull(mtg3,0) as mtg3,
          isnull(mtg4,0) as mtg4,
          total
   from cte
   order by 1