SELECT嵌套在WITH语句中

时间:2020-01-30 01:07:57

标签: sql

我不确定如何在不引起混淆的情况下提出此问题,但让我尝试用我的代码的简化版本进行演示(因为我的代码太长了,很可能会在这一点上使问题感到困惑)。

我有一个WITH语句,该语句定义了多个CTE,在最后一个CTE中,我有一个CASE语句,该语句采用了早期CTE的值,但是由于某种原因,它引发了错误:

The multi-part identifier "RESULT1.total_revenue" could not be bound.

我的代码大致如下(简化):

; with RESULT1 as (
        some code here which returns the columns: client_id, employee_name, total_revenue
        ),
    RESULT2 as (
        some code here which uses the client_id and employee_name from RESULT1 to get employee_team_names from another table employee_teams via a join
        ),
    RESULT3 as (
        some code here which then uses RESULT2 to then get the client_names from another table for each of the client_id found above
        ),
    RESULT4 as (
        now the problem here. I want to then take the client_names found above and do a join in another table to find clean_client_names
        however, if RESULT1.total_revenue is 0, then we can just put 'Not Needed' into the clean_client_name field
        my attempted code below which is throwing the error shown above

        select RESULT3.*,
                    (case when RESULT1.total_revenue = 0 then 'Not Needed' else clean_names_lookup_table.clean_client_name end) as clean_client_name
            from RESULT3
            left join clean_names_lookup_table
            on RESULT3.client_name = clean_names_lookup_table.client_name
        )

2 个答案:

答案 0 :(得分:1)

这是您的CTE:

 select RESULT3.*,
                (case when RESULT1.total_revenue = 0 then 'Not Needed' else clean_names_lookup_table.clean_client_name end) as clean_client_name
 from RESULT3 left join
      clean_names_lookup_table
      on RESULT3.client_name = clean_names_lookup_table.client_name

引用RESULT1尚未定义。您只能引用FROM子句中定义的表别名。 FROM子句中没有这个名称。

您有两种选择:

  1. JOIN中的RESULT1,因此引用有效。
  2. 将您想要的列添加到RESULT2RESULT3中,以便将其作为RESULT3的一部分。

答案 1 :(得分:1)

您需要在JOIN查询中RESULT1RESULT4,否则RESULT1是未知的。大概RESULT3也有一个名为client_id的字段,在这种情况下,您将编写:

    select RESULT3.*,
                (case when RESULT1.total_revenue = 0 then 'Not Needed' else clean_names_lookup_table.clean_client_name end) as clean_client_name
        from RESULT3
        join RESULT1 on RESULT1.client_id = RESULT3.client_id
        left join clean_names_lookup_table
        on RESULT3.client_name = clean_names_lookup_table.client_name
相关问题