使用OVER&的SQL Correlation错误SELECT语句中的PARTITION

时间:2015-01-18 16:54:50

标签: sql window-functions sybase-asa

当我尝试执行SQL SELECT语句时,我收到以下错误

Could not execute statement.
Correllation name 'contact' not found
SQLCODE=-142, ODBC 3 State"42S02"
Line 1, Column 1

我的代码如下

Select forename, surname, email, quotedate
From ( SELECT  *, ROW_NUMBER() OVER (PARTITION BY tblQuote.contno ORDER BY quoteno DESC) AS rn
FROM dba.quotehdr as tblQuote left join dba.contact as tblContact on tblQuote.contno = tblContact.contno)q
where rn = 1 and quotedate <=today()-720 and emailbounced = 0 and email is not null and dba.contact.statusflag = 'A'
order by quotedate desc

此错误仅在我添加

时才会出现
dba.contact.statusflag = 'A'

我试过这个

tblContact.statusflag = 'A'  

我得到同样的错误!

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

q.statusflag = 'A'如何,因为您似乎使用q作为别名。)这个原始答案不正确,修改为:

@Shannon Severance的评论是正确的。您正在尝试在外部查询上使用Where子句 - 该子句不包含联系人表中的任何字段。让我整理你的查询以帮助你看到你的子查询(q) - 如:

Select 
  forename
  ,surname
  ,email
  , quotedate
From 
  (
    SELECT 
      *
      , ROW_NUMBER() OVER (PARTITION BY tblQuote.contno ORDER BY  quoteno DESC) AS rn
    FROM dba.quotehdr as tblQuote 
    left join dba.contact as tblContact on tblQuote.contno = tblContact.contno
  ) q
left join dba.contact as tblContact on q.contno = tblContact.contno
where rn = 1 
  and quotedate <=today()-720 
  and emailbounced = 0 
  and email is not null 
  and tblContact.statusflag = 'A' -- Now sourced from last left join

order by quotedate desc

LEFT JOIN表格上需要另一个dba.contact才能访问此字段(现在仅作为示例添加)。

此外,根据您的数据库引擎 - 如果您的字段在两个表中都是重复的,则子查询中的SELECT *可能会弹出这些字段,或重命名它们,或者抛出错误。单独运行内部子查询并查看它产生的内容,或使用显式字段名称而不是*

(我仍然认为你的子查询中的*导致错误和混乱。删除它并替换table.field名称 - 这将帮助你理解出错的地方......否则你的查询逻辑很漂亮很好,并添加我建议的额外左连接是矫枉过正的)