SELECT嵌套在WITH语句中

问题描述 投票:0回答:2

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

我有一个定义多个CTE的WITH语句,并且在最后一个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
        )

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

sql
2个回答
0
投票

这是您的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

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.