如何在SQL Server中加入2个查询后的值

时间:2015-06-04 08:03:15

标签: sql-server

我希望在总和列NUM_TM后加入2个查询....

SELECT 
    CON_NO, EXP_DT, NTE_DR, DKD_ID
FROM 
    FILB01B
WHERE 
    NUM_TM = (SELECT MAX(NUM_TM) FROM FILB01B WHERE DKD_ID = 'BL') 
    AND DKD_ID = 'BL' 

UNION

SELECT 
    CON_NO, EXP_DT, NTE_DR, DKD_ID
FROM 
    FILB01B
WHERE 
    NUM_TM = (SELECT MAX(NUM_TM) FROM FILB01B WHERE DKD_ID = 'DC') 
    AND DKD_ID = 'DC' 

UNION

SELECT 
    CON_NO, EXP_DT, NTE_DR, DKD_ID
FROM 
    FILB01B
WHERE 
    NUM_TM = (SELECT MAX(NUM_TM) FROM FILB01B WHERE DKD_ID = 'TU' ) 
    AND DKD_ID = 'TU' 
SELECT 
    DKD_ID, SUM(AMT_QT) AS AMT_QT 
FROM 
    FILB01B 
WHERE 
    DKD_ID ='BL' 
GROUP BY 
    DKD_ID 

UNION

SELECT 
    DKD_ID, SUM(AMT_QT) AS AMT_QT 
FROM 
    FILB01B 
WHERE 
    DKD_ID ='DC' 
GROUP BY 
    DKD_ID 

UNION

SELECT 
    DKD_ID, SUM(AMT_QT) AS AMT_QT 
FROM 
    FILB01B 
WHERE 
    DKD_ID = 'TU' 
GROUP BY 
    DKD_ID

1 个答案:

答案 0 :(得分:0)

你的意思是这样吗?

SELECT  *
FROM    
(
    SELECT CON_NO,EXP_DT,NTE_DR,DKD_ID
    FROM FILB01B
    WHERE NUM_TM = (SELECT MAX(NUM_TM) FROM FILB01B WHERE DKD_ID = 'BL') AND DKD_ID = 'BL' UNION
    SELECT CON_NO,EXP_DT,NTE_DR,DKD_ID
    FROM FILB01B
    WHERE NUM_TM = (SELECT MAX(NUM_TM) FROM FILB01B WHERE DKD_ID = 'DC') AND DKD_ID = 'DC' UNION
    SELECT CON_NO,EXP_DT,NTE_DR,DKD_ID
    FROM FILB01B
    WHERE NUM_TM = (SELECT MAX(NUM_TM) FROM FILB01B WHERE DKD_ID = 'TU' ) AND DKD_ID = 'TU'
) a
    inner join 
        (
            SELECT  *
            FROM    
            (
                SELECT DKD_ID,SUM(AMT_QT) AS AMT_QT FROM FILB01B WHERE DKD_ID ='BL' GROUP BY DKD_ID UNION
                SELECT DKD_ID,SUM(AMT_QT)AS AMT_QT FROM FILB01B WHERE DKD_ID ='DC' GROUP BY DKD_ID UNION
                SELECT DKD_ID,SUM(AMT_QT)AS AMT_QT FROM FILB01B WHERE DKD_ID ='TU' GROUP BY DKD_ID
            ) b
        ) b
        on a.YourKey = b.YourKey