SQL返回事务表与前一次付款的日期

时间:2011-06-21 13:13:26

标签: sql ms-access greatest-n-per-group

我在Access中有一个查询,它返回所有客户的交易 这些字段是

TransID,TenantID,TransactionType,Amount,TransactionDate

其中TransactionType = 1表示费用,2表示付款

我想返回此查询的所有记录,其中包含此clinet的先前付款(TransactionType = 2)TransactionDate的额外字段(TenantID) 如果没有先前的付款,我想只返回带有null的记录作为上一个交易日期。

你能帮我吗?

4 个答案:

答案 0 :(得分:2)

使用子查询,传入外部查询的交易日期:

SELECT TransID, TenantID, TransactionType, Amount, TransactionDate,
       (SELECT MAX(I.TransactionDate)
        FROM unnamed_table I
        WHERE I.TransactionDate < O.TransactionDate
          AND I.TransactionType = 2
          AND I.TenantID = O.TenantID) PrevTransDate
FROM unnamed_table O

答案 1 :(得分:0)

你需要一个子查询,或者你需要在MAX和字符串函数中做一些神奇的工作,以便在一个查询中做得更好,或者你需要一个唯一标识前一个事务的id。

select t.*, MAX(prevt.transid) as prev_trans_id
from transactions t 
left join transactions prevt
on t.tenantid=prevt.tenantid 
and t.transid > prevt.transid
group by t.transid

答案 2 :(得分:0)

select t1.TransID, t1.TenantID, t1.TransactionType, t1.Amount, t1.TransactionDate,  max(t2.TransactionDate)
from table as t1 left outer join table as t2 on (t1.TenantID=t2.TenantID)
Where t1.TransactionType =1 and t2.TransactionType =2
and t1.TransactionDate > t2.TransactionDate

答案 3 :(得分:0)

另一种方法:

SELECT
    T1.TransID,
    T1.TenantID,
    T1.TransactionType,
    T1.Amount,
    T1.TransactionDate,
    T2.TransactionDate AS PreviousPaymentDate
FROM
    Transactions T1
LEFT OUTER JOIN Transactions T2 ON
    T2.TenantID = T1.TenantID AND
    T2.TransactionType = 2 AND
    T2.TransactionDate < T1.TransactionDate
LEFT OUTER JOIN Transactions T3 ON
    T3.TenantID = T1.TenantID AND
    T3.TransactionType = 2 AND
    T3.TransactionDate < T1.TransactionDate AND
    T3.TransactionDate > T2.TransactionDate
WHERE
    T3.TransID IS NULL AND
    <your normal selection criteria>

你基本上得到同一租户的类型2的最后一个事务(T2),其中该租户没有其他事务,并且在那个事件之后没有出现相同类型2(这就是T3.TransID IS NULL所做的事情 - 唯一的方法是NULL,如果没有找到匹配项)。您也可以使用NOT EXISTS更清楚地完成此操作,但使用双LEFT OUTER JOIN时性能通常会更好。这是一个NOT EXISTS版本:

SELECT
    T1.TransID,
    T1.TenantID,
    T1.TransactionType,
    T1.Amount,
    T1.TransactionDate,
    T2.TransactionDate AS PreviousPaymentDate
FROM
    Transactions T1
LEFT OUTER JOIN Transactions T2 ON
    T2.TenantID = T1.TenantID AND
    T2.TransactionType = 2 AND
    T2.TransactionDate < T1.TransactionDate
WHERE
    NOT EXISTS (
        SELECT *
        FROM Transactions T3
        WHERE
            T3.TenantID = T2.TenantID AND
            T3.TransactionType = 2 AND
            T3.TransactionDate < T1.TransactionDate AND
            T3.TransactionDate > T1.TransactionDate
        ) AND
    <your normal selection criteria>