我有一个类似以下的SQL查询:
select
,c.customer_leg1
,d.mid
,c.previous_customer_leg1
,c.creation_date
,c.end_date
,c.cid
from table1 c
JOIN table2 d
ON c.cid = d.cid
where c.cid = '1234'
给出了以下输出:
customer_leg1 | previous_customer_leg1 | creation_data | end_date | cid
4092 | 1888 | 05/06/17 | 05/07/17 | 735
8915 | 4092 | 05/06/17 | 05/08/17 | 735
我想添加一个新列,以便我们在customer_leg1
中找到的每个previous_customer_leg1
都应该将该行"end_date"
放在该列中。
例如:在上面的输出customer_leg1
的第1行中4092
是previous_customer_leg1
的第2行,因此在第1行中,new_column
应该有05/08/17
。对于那些customer_leg1在previous_customer_leg1中不匹配的那些,它应该是NULL。我想我可以使用分区和滞后功能,但我对此并不十分清楚。任何帮助将不胜感激。谢谢!
答案 0 :(得分:0)
因为你只是在展示"要点"你想要什么,或许"要点"一种可能的解决方案是这样的:
加入你的"真的很大"查询另一个连接:
select .....
, c1.end_date as new_column
from table1 c join table2 d on c.cid = d.cid
join talbe1 c1 on c.cid = c1.cid
and c.customer_leg1 = c1.previous_customer_leg1
..................
答案 1 :(得分:0)
正如我在评论中提到的那样,您将确保正确显示next row
的列是什么,因为您无法保证输出始终处于相同的顺序。因此,假设您的order
列为creation_date
,并且您希望在partition
c.cid
上完成此操作,则可以向{{1}添加以下内容}}语句来派生这个新列,而不会干扰查询的其余部分。
免责声明:如果select
和partition
的列不相同,那么这将无效。请更改列。但是读取列的下一行并且如果匹配,然后显示下一行的另一列的概念如下。
order