在SQL Server 2008中加入三个表

时间:2021-01-03 17:00:49

I have three tables.

我有三张桌子。

A

一个

ID   NAME  
---  ----   
1    abc   
2    asd  
3    qwe

B

ID    INCOME  
---   ------  
1      2  
2      3  
1      4

C

C

NAME   TOTAL  
----  ----    
abc    8  
asd    20

I want to join this three tables with a SQL query to produce an output like

我想用SQL查询连接这三个表来产生类似的输出

ID INCOME TOTAL  
---------------
1    6       8  
2    3      20

Could anyone help me?

谁能帮助我?

1 个解决方案

#1


0  

You could try this:

你可以试试这个:

select 
    t1.id, sum(t2.income) income, sum(t3.total) total
from 
    table1 t1 
join 
    table2 t2 on t1.id = t2.id
join 
    table3 t3 on t3.name = t1.name
group by 
    t1.id
order by 
    t1.id

#1


0  

You could try this:

你可以试试这个:

select 
    t1.id, sum(t2.income) income, sum(t3.total) total
from 
    table1 t1 
join 
    table2 t2 on t1.id = t2.id
join 
    table3 t3 on t3.name = t1.name
group by 
    t1.id
order by 
    t1.id