2012-12-05 241 views
3

如何合併以下兩個查詢,以便我可以獲得兩列PAYMODE 和PAYTYPE。兩個查詢都是相似的,並且是相同的表。將兩個sql查詢組合成一個查詢,以便我不需要執行兩個單獨的查詢。將兩個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' 
+0

製作UNION –

+0

使用'或':'AND((X = 'PMODE' 和y = 'RC')或(x = 'PTYPE' 和y = 'ER'))' –

回答

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

爲了清楚起見,當條件具有「OR」時,請始終使用括號。而在DB2中,表引用是_always_必需的(您的第一個查詢會引發錯誤 - 您可以使用'sysibm/sysdummy1')。 –

+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。兩個查詢的

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'