sql查询获得ID明智的平衡

时间:2013-03-21 06:22:28

标签: sql oracle oracle10g

我有以下SQL查询:( Oracle 10

SELECT
     A.ID,
     SUM(A.AMT_CR) - SUM(A.AMT_DR) AS balAmt,
     P.NAME
FROM TABLE1 A, TABLE2 P
WHERE P.ID BETWEEN 'C0100' AND 'C0200'
    AND P.ID = A.ID
    AND A.TRANS_DATE < '01-FEB-2013'
GROUP BY A.ID, P.NAME
ORDER BY A.ID

以上查询执行得很好,但此查询的条件为AND A.TRANS_DATE < '01-FEB-2013'。这条件适用于在balAmt之前获取TRANS_DATE。但是此查询的问题在于,它只会获得IDs条件AND A.TRANS_DATE < '01-FEB-2013'。如果ID没有TRANS_DATE小于'01-FEB-2013',则它不会显示该ID的记录。

所以我想从数据库中获取All IDs。但我希望balAmt条件AND A.TRANS_DATE < '01-FEB-2013'得到{{1}}。

任何建议都将受到赞赏。

提前致谢。

3 个答案:

答案 0 :(得分:1)


SELECT Q.ID, W.balmt, W.NAME
FROM TABLE1 Q
LEFT JOIN (
SELECT
     A.ID,
     SUM(A.AMT_CR) - SUM(A.AMT_DR) AS balAmt,
     P.NAME
FROM TABLE1 A, TABLE2 P
WHERE P.ID BETWEEN 'C0100' AND 'C0200'
    AND P.ID = A.ID
    AND A.TRANS_DATE < '01-FEB-2013'
GROUP BY A.ID, P.NAME
) W
ON Q.ID = W.ID
ORDER BY A.ID

答案 1 :(得分:1)

SELECT
     A.ID,
     SUM(case when A.TRANS_DATE < '01-FEB-2013' 
         then nvl(A.AMT_CR,0) - nvl(A.AMT_DR,0)
         else 0
         end) AS balAmt,
     P.NAME
FROM TABLE1 A, TABLE2 P
WHERE P.ID BETWEEN 'C0100' AND 'C0200'
    AND P.ID = A.ID
GROUP BY A.ID, P.NAME
ORDER BY A.ID

答案 2 :(得分:1)

这应该做:

SELECT
     A.ID,
     SUM(A.AMT_CR) - SUM(A.AMT_DR) AS balAmt,
     P.NAME
FROM TABLE1 A
LEFT JOIN TABLE2 P ON P.ID = A.ID
                   AND A.TRANS_DATE < '01-FEB-2013'
                   AND P.ID BETWEEN 'C0100' AND 'C0200'
GROUP BY A.ID, P.NAME
ORDER BY A.ID