Teradata相关子查询

时间:2015-08-18 09:08:24

标签: sql subquery max teradata

我在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匹配&lt; date2而不是max(date1)&lt; date2这就是为什么我有几个amount1

提前感谢帮助:) 祝你有个美好的一天!

2 个答案:

答案 0 :(得分:0)

最终查询:

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

答案 1 :(得分:0)

您可以使用窗口聚合函数访问上一行的数据,Teradata中没有LEAD / LAG,但它很容易重写。

这将为您的示例返回正确的数据:

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 '2015-07-31'