2010-09-14 48 views
0

我有两个表需要连接,然后具有与表2中相同的crb_pi_id的多行结果将组合并作为单行返回。有可能的?我在可打印的报告上使用了该结果。连接表并返回具有相同主ID的多行作为单行

在此先感谢。

表1:

crb_pi_id,name,tel_no 
1,john,1111111 
2,paul,2222222 

表2:

crb_pd_id,crb_pi_id,account_name,amount 
1,1,salary,500 
2,1,utilities,800 
3,2,transportation,300 

结果应该

name,salary,utilities,trasportation 

john,500,800,0 
paul,0,0,300 

回答

0
select a.name, a.tel_no, sum(b.amount) as totamount 

from table1 a left outer join table2 b on a.crb_pi_id = b.crb_pi_id 
group by a.name, a.tel_no 

你必须包括任何从table1中的字段,你在选择组中的语句列表

+0

喜拉吉,我想多行输出在一个单一的行合并,但应在不同的显示领域柱。 – tirso 2010-09-17 02:28:46

0

不知道你能真正做到这一点瓦特/直接的SQL除了使用光标和临时变量被分配的每个单元值的值依次。或者如果您可以使用更高级别的语言,则可以在查询调用的数组中使用php的implode()和字符串concat组合。

编辑1:哦,没关系...权改变的问题后,我贴我的答案哈哈

编辑2:也许你想这样的事情? (未经测试的伪)

select 
    t1.name, 
    case when (t2.crb_pi = t1.crb_pi) and (t2.account_name = 'salary') then t2.amount else 0 end as 'salary' 
    case when (t2.crb_pi = t1.crb_pi) and (t2.account_name = 'utilities') then t2.amount else 0 end as 'utilities' 
    case when (t2.crb_pi = t1.crb_pi) and (t2.account_name = 'transportation') then t2.amount else 0 end as 'transportation'  
from table1 t1 
left join table2 t2 
    on t2.crb_pi = t1.crb_pi 
+0

对不起,重复编辑和取消删除。新的这个网站,仍然搞清楚如何做的东西与回应&评论和东西:) – alien052002 2010-09-14 06:38:00

+0

嗨外星人,我试过你的代码,但输出仍然多行。这里是我根据您的建议选择的代码 t1.name, case when when(t2.crb_pi_id = t1.crb_pi_id)and(t2.account_code ='salary')then then2.amount else 0 end as'salary', (t2.crb_pi_id = t1.crb_pi_id)和(t2.account_code ='utilities')的情况下,则t2.amount else 0结束为'utilities', case when(t2.crb_pi_id = t1.crb_pi_id)and(t2。 ACCOUNT_CODE =“交通运输类”),然后t2.amount否则为0结束从crb_personal_info T1 左加入crb_personal_details T2 上t2.crb_pi_id = t1.crb_pi_id – tirso 2010-09-17 02:25:33

0

您可以子句在这里使用,然后组的结果也相应

select t1.name 'name', t2.amount 'salary', 
CASE WHEN t2.crb_pi_id=t1.crb_pi_id and t2.crb_pd_id=2 then t2.amount ELSE 0 END 'utilities', 
CASE WHEN t2.crb_pi_id=t1.crb_pi_id and t2.crb_pd_id=3 then t2.amount ELSE 0 END 'trans' 
into #t3 
from #t1 t1 inner join #t2 t2 on t1.crb_pi_id=t2.crb_pi_id 

select name, max(salary), max(utilities), max(trans) 
from t3 
group by name 
+0

喜阿尼尔,Itried你的代码,但出现了一个错误,说“交通运输类” (# 1064 - 您的SQL语法错误;检查与您的MySQL服务器版本相对应的手册,以找到在'WITH t3(name,salary,utilities)附近使用的正确语法a s ( select t1.name,t2.amount'salary', C'at line 1) – tirso 2010-09-17 02:27:39

+0

我的错误.. mySQL不支持WITH子句。所以你可以使用临时表。我编辑了我的帖子。 #t1和#t2代表你的两个表格 – 2010-09-17 05:34:04