在sybase中重建窗口函数row_number
Posted
技术标签:
【中文标题】在sybase中重建窗口函数row_number【英文标题】:Rebuild window function row_number in sybase 【发布时间】:2014-10-14 18:31:03 【问题描述】:如果我在 Sybase 中有可用的窗口函数,我可以轻松解决一个问题,但我没有:
考虑一个表test
:
+------------+----------------+-------------+
| Account_Id | Transaction_Id | CaptureDate |
+------------+----------------+-------------+
| 1 | 1 | 2014-01-01 |
| 1 | 2 | 2013-12-31 |
| 1 | 3 | 2015-07-20 |
| 2 | 1 | 2012-02-20 |
| 2 | 2 | 2010-01-10 |
| ... | ... | ... |
+------------+----------------+-------------+
我想为每个帐户获取一个结果集,其中包含最新的CaptureDate
和对应的Transaction_Id
。使用窗口函数row_number
这很容易:
select Accounts_Id, CaptureDate, Transaction_Id from
(select
CallAccounts_Id,
CaptureDate,
Transaction_Id,
ROW_NUMBER() OVER(partition by Accounts_Id order by CaptureDate desc) row
from test) tbl
where tbl.row = 1
但是我的sybase 版本没有这个。很明显,喜欢……
select max(Transaction_Id ), max(Transaction_Id ), Account_Id
from test
group by Account_Id
不起作用,因为它并不总是给我正确的 Transaction_Id。 我怎样才能在 Sybase 中做到这一点而不让它变得非常冗长?
谢谢!
【问题讨论】:
【参考方案1】:试试下面:
SELECT Account_Id, Transaction_Id, CaptureDate
FROM test a
WHERE CaptureDate = (
SELECT MAX(CaptureDate)
FROM test b
WHERE a.Account_Id = b.Account_Id
)
编辑 1: Duplicate CaptureDate 不在您的示例中,因此我没有处理这种情况。试试下面:
SELECT Account_Id, Transaction_Id, CaptureDate
FROM test a
WHERE CaptureDate = (
SELECT MAX(CaptureDate)
FROM test b
WHERE a.Account_Id = b.Account_Id
)
AND Transaction_Id =
(
SELECT MAX(Transaction_Id)
FROM test c
WHERE a.Account_Id = c.Account_Id
AND a.CaptureDate = c.CaptureDate
)
【讨论】:
好的,谢谢!但是如何处理相同的 CaptureDate(在这种情况下取更高的 Transaction_Id)?对于这种情况,我只想要一个结果行以上是关于在sybase中重建窗口函数row_number的主要内容,如果未能解决你的问题,请参考以下文章