简体   繁体   English

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

[英]Combine two sql queries into one query

How can I combine following 2 queries so that I can get two columns PAYMODE and PAYTYPE. 如何组合以下2个查询,以便我可以获得两列PAYMODE和PAYTYPE。 Both queries are similar and for same table.Combine two sql queries into one query so that I don't need to execute two separate queries. 两个查询都是相似的并且对于同一个表。将两个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'

Since the records appear in different rows of the source data, I will be difficult to retrieve them in a single result row. 由于记录显示在源数据的不同行中,因此我很难在单个结果行中检索它们。 You can get the results in a single query that gives you two rows. 您可以在一个查询中获得结果,该查询为您提供两行。 Try this: 尝试这个:

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

The first row will contain the paymode, and the second row will contain the paytype. 第一行将包含paymode,第二行将包含paytype。

you always can do this 你总能做到这一点

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

In SQL Server you can do this (Can't test it in DB2, sorry) 在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')
             )
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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM