2012-07-20 73 views
0

我想在应该在SQL中处理的代码中处理此问题。问题是我想拿这个SQL与特定匹配列合并行

ID COL 1 | ID COL 2 | CHARGE |付款

2 |  3 | 17 |  0 
2 |  3 | 0  |  17 

,并把它变成这个

ID COL 1 | ID COL 2 | CHARGE |付款

2 |  3 | 17 | 17 

table1的

ID |无论|无论1

5 | null | null

table2

id | id col 1 | id col 2 |收取|付款

5 | 2 | 3 | 17 | 0

5 | 2 | 3 | 0 | 17

当前结果:

id |无论| whatever1 | idcol1 | idcol2 |收取|付款

5 | null | null | 2 | 3 | 17 | 0

5 | null | null | 2 | 3 | 0 | 17

想要:

ID |无论| whatever1 | idcol1 | idcol2 |收取|付款

5 | 2 | 3 | 17 | 17

问题是在我的SQL调用期间我正在做一个内部联接,它为一些值做了笛卡尔积,而不是做上面我想要的。有没有人有一个想法如何完成?

+2

请!向我们展示你的SQL! – 2012-07-20 00:47:40

回答

2

您可以通过这个用组:

select IDCOL1, IDCOL2, max(CHARGE) as charge, max(PAYMENT) as payment 
from table t 
group by idcol1, idcol2 

这得到了最大充电和最高支付限额从具有相同ID列的所有行。如果您有多行费用或付款,您可能更喜欢SUM()MAX()。

随着加入,这将是这样的:

select t1.id, t1.whatever, t1.whatever, t2.IDCOL1, t2.IDCOL2, 
     max(CHARGE) as charge, max(PAYMENT) as payment 
from table1 t1 join 
    table2 t2 
    on t1.id = t2.id 
group by t1.id, t1.whatever, t1.whatever, t2.IDCOL1, t2.IDCOL2 
+0

最大功能和分组,应该有这个想法。你是男人,非常感谢你! – bluefear 2012-07-20 01:10:32