"第一顺序由"在Teradata

时间:2016-11-28 14:32:08

标签: sql oracle teradata row-number

我在将SQL语句从Oracle转换为Teradata时遇到问题。在Oracle声明中是:

SELECT ar.account_no,
MAX (ah.bal_acct) KEEP (DENSE_RANK FIRST ORDER BY ah.created_t desc) 
FROM ar
   JOIN ah ON ah.obj_id0 = ar.poid_Id0
   JOIN acc ON a.poid_id0 = ar.account_obj_Id0
WHERE acc.account_no = '1234'
AND ah.created_t <= 1434753495
GROUP BY ar.account_no

我需要在Teradata中做类似的陈述。我试过

QUALIFY ROW_NUMBER() OVER( PARTITION BY max(ah.bal_acct) ORDER BY ah.created_t desc) = 1

但是我一直有错误:选定的非聚合值必须是关联组的一部分。

这就是我得到的:

Select ar.account_no, ah.created_t, ah.bal_acct
FROM VD_REPLICA_BRM.pi_tp_acct_ar_t ar
    JOIN VD_REPLICA_BRM.pi_tp_acct_ar_hist_T ah ON ah.obj_id0 = ar.poid_Id0
    JOIN VD_REPLICA_BRM.pi_account_t acc ON acc.poid_id0 = ar.account_obj_Id0
WHERE acc.account_no = '00003095660515'
    AND ah.created_t <= CAST('2016-10-31' AS DATE FORMAT 'YYYY-MM-DD')
QUALIFY ROW_NUMBER() OVER( PARTITION BY max(ah.bal_acct) ORDER BY ah.created_t desc) = 1
GROUP BY ar.account_no

我在哪里做错了?

1 个答案:

答案 0 :(得分:2)

我不确定你是否可以使用qualify执行此操作。一个等价的陈述是:

SELECT ar.account_no, ah.created_t, ah.bal_acct
FROM (SELECT ar.account_no, ah.created_t, ah.bal_acct,
             ROW_NUMBER() OVER (PARTITION BY ar.account_no ORDER BY ah.created_t DESC) as seqnum
      FROM ar JOIN
           ah
           ON ah.obj_id0 = ar.poid_Id0 JOIN
           acc
           ON a.poid_id0 = ar.account_obj_Id0
      WHERE acc.account_no = '1234' AND ah.created_t <= 1434753495
     ) t
WHERE seqnum = 1;

咄。您可以使用QUALIFY执行此操作。问题是GROUP BY

SELECT ar.account_no, ah.created_t, ah.bal_acct
FROM VD_REPLICA_BRM.pi_tp_acct_ar_t ar JOIN
     VD_REPLICA_BRM.pi_tp_acct_ar_hist_T ah
     ON ah.obj_id0 = ar.poid_Id0 JOIN
     VD_REPLICA_BRM.pi_account_t acc
     ON acc.poid_id0 = ar.account_obj_Id0
WHERE acc.account_no = '00003095660515' AND
      ah.created_t <= CAST('2016-10-31' AS DATE FORMAT 'YYYY-MM-DD')
QUALIFY ROW_NUMBER() OVER( PARTITION BY ar_account_no ORDER BY ah.created_t desc) = 1