将两个sql查询合并到一个查询中

时间:2012-12-05 07:19:43

标签: sql db2

如何组合以下2个查询,以便我可以获得两列PAYMODE  和PAYTYPE。两个查询都是相似的,对于同一个表。将两个sql查询合并为一个查询,这样我就不需要执行两个单独的查询。

SELECT ETBL_DESC_TXT as PAYMODE
FROM tedit
WHERE CO_ID = 'CP'
AND   ETBL_TYP_ID = 'PMODE'
AND   ETBL_VALU_ID = 'RC'


select ETBL_DESC_TXT as PAYTYPE
FROM tedit
WHERE CO_ID = 'CP'
AND   ETBL_TYP_ID = 'PTYPE'
AND   ETBL_VALU_ID = 'ER'

3 个答案:

答案 0 :(得分:1)

由于记录显示在源数据的不同行中,因此我很难在单个结果行中检索它们。您可以在一个查询中获得结果,该查询为您提供两行。试试这个:

SELECT ETBL_DESC_TXT as PAYFIELD
FROM tedit
WHERE CO_ID = 'CP' AND (
      (ETBL_TYP_ID = 'PMODE' AND ETBL_VALU_ID = 'RC')
   OR (ETBL_TYP_ID = 'PTYPE' AND ETBL_VALU_ID = 'ER')
)
ORDER BY ETBL_TYP_ID

第一行将包含paymode,第二行将包含paytype。

答案 1 :(得分:0)

你总能做到这一点

select
    (
        SELECT ETBL_DESC_TXT
        FROM tedit
        WHERE CO_ID = 'CP'
        AND   ETBL_TYP_ID = 'PMODE'
        AND   ETBL_VALU_ID = 'RC'
    ) as PAYMODE,
    (    
        select ETBL_DESC_TXT
        FROM tedit
        WHERE CO_ID = 'CP'
        AND   ETBL_TYP_ID = 'PTYPE'
        AND   ETBL_VALU_ID = 'ER'
    ) as PAYTYPE
from SYSIBM.SYSDUMMY1

在SQL Server中,您可以执行此操作(无法在DB2中测试,抱歉)

        SELECT
            max(case when ETBL_VALU_ID = 'RC' and ETBL_TYP_ID = 'PMODE' then ETBL_DESC_TXT else null end) as PAYMODE,
            max(case when ETBL_VALU_ID = 'ER' and ETBL_TYP_ID = 'PTYPE' then ETBL_DESC_TXT else null end) as PAYTYPE
        FROM tedit
        where 
            CO_ID = 'CP' and
            (
                 (ETBL_VALU_ID = 'RC' and ETBL_TYP_ID = 'PMODE') or
                 (ETBL_VALU_ID = 'ER' and ETBL_TYP_ID = 'PTYPE')
             )

答案 2 :(得分:0)

SELECT 'PAYMODE' as RowType,ETBL_DESC_TXT as PayValue
FROM tedit
WHERE CO_ID = 'CP'
AND   ETBL_TYP_ID = 'PMODE'
AND   ETBL_VALU_ID = 'RC'

union all

select 'PAYTYPE' as RowType, ETBL_DESC_TXT as PayValue
FROM tedit
WHERE CO_ID = 'CP'
AND   ETBL_TYP_ID = 'PTYPE'
AND   ETBL_VALU_ID = 'ER'