代码之家  ›  专栏  ›  技术社区  ›  Gowtham SB

在具有不同列的where子句中无法识别别名RANK()函数

  •  0
  • Gowtham SB  · 技术社区  · 6 年前

    我有两个列表(customer、position、product、sales\u cycle、call\u count、cntry\u cd、owner\u cd、cr8),我面临以下挑战,请帮助我解决此问题

    我的要求

    我有两张测试表。表1和试验。表2

    我需要通过使用“test.table1”进行选择来从“test.table2”中插入值。但我面临一个问题,即在将数据加载到“test.table2”时,我得到了一些重复数据

    我在这两个表中总共有8列,但在加载时,我需要在“call\u count”列中取最高位,条件是这些列的值唯一(customer、position、product、sales\u cycle)

    询问我尝试了什么

    select 
    distinct (customer, position, product ,sales_cycle), 
    rank () over (order by call_count desc) rnk, 
    cntry_cd, 
    owner_cd, 
    cr8 
    from test.table1 
    where rnk=1
    

    在上述查询中,我面临的挑战很少(我使用的数据库是红移)

    1、我不能只对几列进行区分

    where子句中无法识别别名“rnk”

    请帮我修一下,谢谢

    1 回复  |  直到 6 年前
        1
  •  4
  •   a_horse_with_no_name    6 年前

    不能在引入列别名的同一级别上使用列别名。您需要将查询包装在派生表中。这个 distinct 如图所示,如果您使用 rank()

    select customer, position, product, sales_cycle, 
           cntry_cd, owner_cd, cr8 
    from (
      select customer, position, product, sales_cycle, 
             cntry_cd, owner_cd, cr8,
             rank () over (order by call_count desc) rnk
      from test.table1 
    ) t 
    where rnk=1;
    

    派生表不会增加处理时间的开销。在这种情况下,允许您引用列别名仅仅是语法上的糖分。