Combine two sql queries into one query

别说谁变了你拦得住时间么 提交于 2019-12-12 16:22:59

问题


How can I combine following 2 queries so that I can get two columns PAYMODE and 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.

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'

回答1:


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.




回答2:


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'



回答3:


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)

        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')
             )


来源:https://stackoverflow.com/questions/13718184/combine-two-sql-queries-into-one-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!