不使用派生表在每个组上排名

时间:2016-11-30 10:11:31

标签: sql oracle teradata

AccountNo           Account Name         Transaction time             Transaction Amount
A01                 Name 1               01-01-2016 04:00:00          5000
A01                 Name 1               01-01-2016 07:30:00          3500
A01                 Name 1               01-01-2016 09:30:00          3500
A01                 Name 1               01-01-2016 12:00:00          6500
A01                 Name 1               02-02-2016 06:00:00          4000
A01                 Name 1               01-02-2016 08:30:00          8000
A01                 Name 1               01-02-2016 09:30:00          8000
A02                 Name 2               05-01-2016 04:00:00          2000
A02                 Name 2               05-01-2016 07:30:00          8500
A02                 Name 2               08-02-2016 06:00:00          1000
A02                 Name 2               09-02-2016 08:30:00          9000

我需要一个查询而不使用派生表来获取每个帐户的最新交易记录。查询应支持OracleTERADATA。 使用Derived表我可以解决它如下:

SELECT a.accountno, 
       a.account_name, 
       a.transaction_time, 
       a.transaction_amount 
FROM   acct_details a, 
       (SELECT accountno, 
               Max(transaction_time) AS Transaction_time 
        FROM   acct_details 
        GROUP  BY accountno) b 
WHERE  a.accountno = b.accountno 
   AND a.transaction_time = b.transaction_time;

感谢您的帮助!!

3 个答案:

答案 0 :(得分:1)

为什么没有Derived Table?

在Teradata有资格,但它没有标准SQL:

SELECT *
FROM   acct_details 
QUALIFY RANK() OVER (PARTITION BY accountno 
                     ORDER BY transaction_time DESC) = 1;

在Oracle中,您需要一个派生表:

SELECT a.accountno, 
       a.account_name, 
       a.transaction_time, 
       a.transaction_amount,
FROM
 ( 
    SELECT a.accountno, 
           a.account_name, 
           a.transaction_time, 
           a.transaction_amount,
           RANK() OVER (PARTITION BY accountno 
                        ORDER BY transaction_time DESC) as rnk
    FROM   acct_details a
 ) a
WHERE rnk = 1

您也可以尝试使用Oracle的MAX / KEEP:

SELECT a.accountno, 
       MAX (a.account_name) KEEP (DENSE_RANK FIRST ORDER BY a.transaction_time desc) , 
       MAX(a.transaction_time), 
       MAX (a.transaction_amount) KEEP (DENSE_RANK FIRST ORDER BY a.transaction_time desc)     FROM  acct_details a
GROUP BY a.accountno

答案 1 :(得分:0)

您可以使用内联视图执行此操作:

SELECT a.accountno, 
       a.account_name, 
       a.transaction_time, 
       a.transaction_amount 
FROM   (SELECT accountno, 
               account_name, 
               transaction_time, 
               transaction_amount, 
               Max(transaction_time) OVER (PARTITION BY accountno) AS max_transaction_time 
        FROM   acct_details) a
WHERE  a.transaction_time = a.max_transaction_time;

这适用于Oracle,我认为它也适用于Teradata。

我在这里假设当你说要避免派生表时,你的意思是你想避免将表连接到自身。

答案 2 :(得分:-1)

尝试此查询:

选择[交易时间],[帐户名称],

领先([交易时间],1,1)OVER(按[账户名称]订购)

FROM [dbo]。[acct_details]

这应该可以帮到你