【问题标题】:Rebuild window function row_number in sybase在sybase中重建窗口函数row_number
【发布时间】: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 中做到这一点而不让它变得非常冗长?

谢谢!

【问题讨论】:

    标签: sybase window-functions


    【解决方案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)?对于这种情况,我只想要一个结果行
    猜你喜欢
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多