1

我有以下 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'。这个条件是为了balAmtTRANS_DATE. 但是这个查询的问题是它只得到IDs相对于AND A.TRANS_DATE < '01-FEB-2013'条件的。如果 aIDTRANS_DATE小于,'01-FEB-2013'则不会显示 that 的记录ID

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

任何建议将不胜感激。

提前致谢。

4

3 回答 3

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

于 2013-03-21T06:39:21.197 回答
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
于 2013-03-21T07:02:13.557 回答
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
于 2013-03-21T07:04:59.840 回答