使用LAG并比较列

时间:2017-09-25 15:19:24

标签: sql postgresql

我使用滞后函数将两个表连接在一起,这样第一个表就不会显示重复的度量标准行。

但是在选择加入时我无法引用滞后列。

我的查询如下,提到的列标有!!!

 select "Campaign",
 "Ad group" ,
 "Final URL" ,
 "Headline 1" ,
 "Headline 2" ,
 "Description" ,
 "Path 1" ,
 "Path 2" ,
 "Status" ,
 "Labels" ,
   case when prev_key is null or prev_key != "Key" then "Clicks" end as 
  "Clicks",
   case when prev_key is null or prev_key != "Key" then "Impressions" end 
  as 
   "Impressions",
      case when prev_key is null or prev_key != "Key" then "Cost" end as 
  "Cost",
    case when prev_key is null or prev_key != "Key" then "Avg. position" end 
 as 
  "Avg. position",
    case when prev_key is null or prev_key != "Key" then "Initial Leads" end 
  as 
   "Initial Leads",
    case when prev_key is null or prev_key != "Key" then "Evaluations" end 
  as 
   "Evaluations",
    case when prev_key is null or prev_key != "Key" then "Won Leads" end as 
  "Won Leads",
    case when prev_key is null or prev_key != "Key" then "Opportunities" end 
   as 
  "Opportunities",
   "Language",
     "Network",
    "Main Keyword",
    "Cluster Keyword 1",
    "Match Type"


    from 

    (SELECT 
  "x"."Campaign",
  "x"."Ad group",
  "x"."Final URL",
 "x"."Headline 1",
 "x"."Headline 2",
 "x"."Description",
 "x"."Path 1",
 "x"."Path 2",
 "x"."Status",
 "x"."Labels",
 !!!lag ("x"."Key") over () AS prev_Key!!!,
 "x"."Clicks",
 "x"."Impressions",
 "x"."Cost",
 "x"."Avg. position",
 "x"."Initial Leads",
 "x"."Evaluations", 
 "x"."Won Leads",
 "x"."Opportunities",
 "x"."Language",
  "x"."Network",
  "x"."Main Keyword",
  "x"."Cluster Keyword 1",
  "x"."Match Type"


   FROM ad_copies_final_joined_concatenated x join 
  ad_copies_final_to_join_concatenated

  using ("Key")

    order by "Campaign" desc, "Key"
   ) sub ;

输出错误消息如下;

  

错误:列“密钥”不存在   第11行:prev_key为null或prev_key的情况!=“Key”然后“Cli ...                                                         ^

1 个答案:

答案 0 :(得分:0)

您不应对字符串和列名使用相同的语法。

我怀疑错误是由于使用双引号和字符串。

尝试将非列的所有内容更改为单引号。

E.G。

case when prev_key is null or prev_key != 'Key' then "Avg. position" end 
as "Avg. position"

或者,您确实希望将prev_key列与Key列进行比较。在这种情况下,您忘记在内部查询中选择Key,因此请将其添加到选择列表中。