从两个表和总和中选择

时间:2017-05-14 12:55:31

标签: sql

我的语法中有一点问题请帮助我。

Table TransM
Code_Project   Code_Name  Code_Stat   Project_Name
17-0004        A          1           ABC  
17-0004        A          2           ABC   
17-0004        B          1           DEF 

Tabel TransW
Code_Project     Code_Name      Total
17-0004          A              1000
17-0004          A              1500
17-0004          A              1200
17-0004          B              1600

我想要的结果是这样的:

Code_Project   Code_Name   Project_Name   GrandTotal
17-0004        A           ABC            3700
17-0004        B           DEF            1600

我使用这种语法并且格式错误

SELECT
  a.Code_Project,
  a.Code_Name,
  a.Project_Name,
  SUM(b.Total) AS GrandTotal
FROM
  TransM a
  INNER JOIN TransW b
    ON a.Code_Project = b.Code_Project
    AND a.Code_Name = b.Code_Name
WHERE a.Code_Project = '17-0004'
GROUP BY a.Code_Project,
  a.Code_Name,
  a.Project_Name

请告诉我正确的语法,谢谢

2 个答案:

答案 0 :(得分:1)

TransM中有多行符合TransW中的多行,因为Code_Project, Code_Name, Project_Name中的TransM不是唯一的。

您可以将distinct设置为子查询/派生表,并使用它进行连接:

select 
    a.Code_Project
  , a.Code_Name
  , a.Project_Name
  , sum(b.Total) as GrandTotal
from (select distinct Code_Project, Code_Name, Project_Name from TransM) a
  inner join TransW b
    on a.Code_Project = b.Code_Project
   and a.Code_Name = b.Code_Name
where a.Code_Project = '17-0004'
group by 
    a.Code_Project
  , a.Code_Name
  , a.Project_Name

如果给定Project_Name的{​​{1}}有多个不同的值,那么您仍会获得重复项。在这种情况下,您需要确定如何选择要返回的Code_Project, Code_Name,或者使用Project_Namemin()来选择一个,如下所示:

max()

rextester演示:http://rextester.com/RRGFQM14769

返回:

select 
    a.Code_Project
  , a.Code_Name
  , a.Project_Name
  , sum(b.Total) as GrandTotal
from (
    select m.Code_Project, m.Code_Name, max(m.Project_Name) as Project_Name
    from TransM m
    group by m.Code_Project, m.Code_Name
    ) a
  inner join TransW b
    on a.Code_Project = b.Code_Project
   and a.Code_Name = b.Code_Name
where a.Code_Project = '17-0004'
group by 
    a.Code_Project
  , a.Code_Name
  , a.Project_Name

答案 1 :(得分:0)

您也可以使用union allgroup by

执行此操作
select Code_Project, Code_Name,
       max(Project_Name) as Project_Name, 
       sum(Total) as GrandTotal
from ((select Code_Project, Code_Name, Project_Name, 0 as Total
       from TransM
      ) union all
      (select Code_Project, Code_Name, NULL Project_Name, Total
       from TransW
      ) 
     ) mw
group by Code_Project, Code_Name;