我有一个问题,如果我在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中执行此操作而不是非常冗长?
谢谢!
答案 0 :(得分: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: 重复的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
)