2017-05-25 50 views
0

值我有一个SQL查询类似如下:如何从另一行获得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"放在该列中。

对于例如:在上面的输出的第1行是customer_leg14092,这在第2行中发现previous_customer_leg1,所以在第1行,这new_column应该有它05/08/17。对于那些customer_leg1在previous_customer_leg1中不匹配的应用程序,它应该为NULL。我想我可能会使用分区和滞后功能,但我对这些并不十分清楚。任何帮助将不胜感激。谢谢!

+0

你根本没有关闭。为什么你认为你需要'lag()'和'partition'?你需要的是自我加入,而不是分析功能。最好只说出你的问题(就像你一样);不包括如何在你的问题陈述中解决它。 (你没有,你只是给你的印象你给的标题。) – mathguy

+0

你发布的查询没有太大意义。你选择的所有列都来自'table1','where'条件也都是基于同一个表,为什么你加入'table2'? – mathguy

+0

,因为实际的查询真的很大,这只是我想要的东西 – Arman

回答

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 
.................. 
+0

你为什么加入c.cid = c1.cid呢? – Arman

+0

我认为cid可能是您的表的主键,而customer_leg1(etc)只是一个属性,可能会在表中出现多次。如果是这样,那么您不想将customer_leg1从一个cid关联到另一个cid的previous_customer_leg1。当然,我的假设可能是错误的,但请记住,它只是一个比你原来的更大的查询的要点。如果你想得到更仔细更详细的答案,你需要提出一个更加细致和详细的问题。 – mathguy

+0

在这样做,我得到“列不明确定义”错误 – Arman

0

正如我在评论中询问的那样,您将确保next row正确显示的列有哪些列,因为您无法保证您的输出始终以相同的顺序显示。因此,假设您的order列为creation_date,并且您希望在的partition上完成此操作,则可以在select语句中添加类似以下内容的内容来派生此列,而不会干扰查询的其余部分。

声明:如果partitionorder的列不相同,那么这将不起作用。请更改列。但的概念读取下一行为一列,如果匹配,则显示下一行以下的另一列。

,CASE 
    WHEN lead (c.previous_customer_leg1,1) 
      over (partition BY c.cid ORDER BY c.creation_date) 
     = c.customer_leg1 
    THEN lead (c.end_date,1) over (partition BY c.cid ORDER BY c.creation_date) 
END AS new_column