SQL 返回带有上次付款日期的交易表
我在 Access 中有一个查询,该查询返回所有客户的交易 字段为
TransID、TenantID、TransactionType、Amount、TransactionDate
其中 TransactionType =1 表示费用,2 表示付款
我想返回此查询的所有记录,并附加一个包含之前付款的 (TransactionType =2 ) TransactionDate 的字段客户端(租户ID) 如果没有之前的付款,我只想返回之前交易日期为空的记录。
你能帮我吗?
I have a query in Access that returns transactions for all customers
the fields are
TransID, TenantID, TransactionType, Amount, TransactionDate
Where TransactionType =1 for Charges and 2 is for payments
I would like to return all the records of this query with an extra field containing the previous payment's (TransactionType =2 ) TransactionDate for this clinet (TenantID)
In case there is no previous payment I would like to just return the record with null as previous transaction date.
Can you help me please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用子查询,传入外部查询的交易日期:
Using a sub-query, pass in the outer query's transaction date:
你需要一个子查询,或者你需要使用 MAX 和字符串函数做一些魔术,以便在一个查询中做得更好,或者你需要一个唯一标识前一个事务的 id。
you'll need a sub query or you'll need to do some magic with MAX and string functions to do better than this in one query or you'll need an id that identifies the previous transaction uniquely.
另一种方法:
您基本上获得同一租户的类型 2 的最后一个事务 (T2),其中该租户的其他事务和相同类型 2 的事务在该事务之后不会出现(这就是 T3.TransID IS NULL 的作用 -如果没有找到匹配项,则它为 NULL 的唯一方法)。您还可以使用 NOT EXISTS 更清楚地做到这一点,但使用双 LEFT OUTER JOIN 的性能通常会更好。这是一个不存在的版本:
Another method:
You're basically getting the last transaction (T2) that's of type 2 for the same tenant where no other transaction for that tenant and of the same type 2 appears after that one (that's what the T3.TransID IS NULL does - the only way that it will be NULL is if no match was found). You can also do this a little more clearly with a NOT EXISTS, but performance is often better with the double LEFT OUTER JOIN. Here's a NOT EXISTS version: