关于自联接的SQL查询

时间:2013-12-03 07:47:33

标签: sql db2

我在db2中有一个sql,如下所示:

SELECT  distinct KEY_COL, MY_TYPE1,
CASE WHEN MY_TYPE2 = 'ONE' THEN COL1 ELSE '' END AS NEWCOL1, 
CASE WHEN MY_TYPE2 = 'ONE' THEN COL2 ELSE '' END AS NEWCOL2, 
CASE WHEN MY_TYPE2 = 'TWO' THEN COL1 ELSE '' END AS NEWCOL3, 
CASE WHEN MY_TYPE2 = 'TWO' THEN COL2  ELSE '' END AS NEWCOL4 
FROM MYSCHEMA.MYTABLE 

从上面的查询中可以看出,根据MY_TYPE2中的MYSCHEMA.MYTABLE列,确定了新的列值。

如果MY_TYPE2为1,则col1col2分别为newcol1newcol2指定给定密钥和MY_TYPE1列。但如果MY_TYPE2对于相同的密钥和MY_TYPE1为两个,则col1col2会转到newcol3newcol4

输出表如下所示:

KEY_COL | MY_TYPE1 | NEWCOL1 | NEWCOL2 | NEWCOL3 | NEWCOL4
=========================================================
 1          T1         1         2
 1          T1                              4          3
 1          T2         2         3                    
 1          T2                              4          1
 ========================================================

但是,我想要一个基于MY_TYPE1列的单行,如下所示:

 KEY_COL | MY_TYPE1 | NEWCOL1 | NEWCOL2 | NEWCOL3 | NEWCOL4
 =========================================================
 1          T1         1         2          4          3
 1          T2         2         3          4          1
 ========================================================

如何修改查询以达到上述效果?

感谢阅读!

2 个答案:

答案 0 :(得分:0)

select key_col, my_type1, max(newcol1), max(newcol2), max(newcol3), max(newcol4) 
from 
(
    SELECT  distinct KEY_COL, MY_TYPE1,
    CASE WHEN MY_TYPE2 = 'ONE' THEN COL1 ELSE '' END AS NEWCOL1, 
    CASE WHEN MY_TYPE2 = 'ONE' THEN COL2 ELSE '' END AS NEWCOL2, 
    CASE WHEN MY_TYPE2 = 'TWO' THEN COL1 ELSE '' END AS NEWCOL3, 
    CASE WHEN MY_TYPE2 = 'TWO' THEN COL2  ELSE '' END AS NEWCOL4 
    FROM MYSCHEMA.MYTABLE
) definedTable
group by key_col, my_type1

答案 1 :(得分:-1)

select KEY_COL ,max(MY_TYPE1),max(NEWCOL1),max(NEWCOL2),max(NEWCOL3),max(NEWCOL4)
from table
group by KEY_COL