Teradata 关联子查询

Teradata Correlated subquery

我在 2 天前就遇到了关于此查询的问题:

select distinct a.id, 
a.amount as amount1, 
(select max (a.date) from t1 a where a.id=t.id and a.cesitc='0' and a.date<t.date) as date1,
 t.id, t.amount as amount2, t.date as date2
 from t1 a
inner join  t1 t on t.id = a.id and  a.cevexp in ('0', '1' )  
and exists  (select t.id from t1 t
where t.id= a.id and t.amount <> a.amount and t.date > a.date) 
and t.cesitc='1' and t.dafms='2015-07-31' and t.date >='2015-04-30' and '2015-07-31' >= t.daefga 
and '2015-07-31' <= t.daecga and t.cevexp='1' and     t.amount >'1'

一些细节,目标是比较资产(id)估值的差异,n2列(a.amount/amount1)是需要修正的。

我希望我的 a.mount/amount1 与我的子查询 'date1' 相关联,但实际上并非如此。必须应用相同的标准才能找到正确的金额 1。 此查询的结果当前显示如下:

Id    Amount1    Date1        id    amount2    date2
1     100       04/03/2014    1     150       30/06/2015
1     102       04/03/2014    1     150       30/06/2015
1     170       04/03/2014    1     150       30/06/2015  

Amount1 匹配所有 Date1 < date2 而不是 max(date1) < date2 这就是为什么我有几个 amount1

在此先感谢您的帮助:) 祝你有美好的一天!

最终查询:

SELECT a.id, a.mtvbie, a.date_valuation, t.id,
MIN(t.amount) -- previous amount
OVER (PARTITION BY t.Id
     ORDER BY t.date_valuation, t.dafms DESC
     ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS prev_amount,
MIN(t.date_valuation) -- previous date
OVER (PARTITION BY t.Id
     ORDER BY t.date_valuation, t.dafms DESC
     ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS prev_date
FROM test5 t
inner join test5 a on a.id=t.id
where t.amount <> a.amount and a.cesitc='1' and a.date_valuation > t.date_valuation and a.dafms ='2015-07-31' and another criteria....
QUALIFY row_number () over (partition by a.id order a.cogarc)=1

您可以使用 Windowed Aggregate Function 访问上一行的数据,Teradata 中没有 LEAD/LAG,但很容易重写。

这将 return 为您的示例提供正确的数据:

SELECT t.*,
   MIN(amount) -- previous amount
   OVER (PARTITION BY Id
         ORDER BY date_valuation, dafms DESC
         ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS prev_amount,
   MIN(date_valuation) -- previous date
   OVER (PARTITION BY Id
         ORDER BY date_valuation, dafms DESC
         ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS prev_date
FROM test5 AS t
QUALIFY cesitc = '1' -- return only the current row

如果它没有按预期工作,您需要添加应用逻辑的更多细节。

顺便说一句,如果列是 DECIMAL,则不应添加引号,150 而不是 '150'。并且只有一种推荐的日期书写方式,使用 date literal,例如DATE '2015-07-31'