简体   繁体   中英

SQL: Converting a Sub-query to a Common Table Expression

I am learning SQL in a course, and I'm working with SQL on MS SQL Server (so, T-SQL). I'm trying to re-factor a sub-query using a common table expression (CTE). Here's the working sub-query version:

SELECT  PAT_ENC_CSN_ID 'CSN',
        ADMISSION_PROV_ID 'Provider ID'

FROM PAT_ENC_HSP

WHERE ADMISSION_PROV_ID IN (
    SELECT DISTINCT PROV_ID
    FROM CL_SER_HIM_LST_VST
    WHERE HIM_STATUS_C <> 1001
    )

I had thought that a CTE was (nearly) a drop-in replacement, so I attempted the following:

WITH Not_Good AS (  SELECT DISTINCT PROV_ID
                    FROM CL_SER_HIM_LST_VST
                    WHERE HIM_STATUS_C <> 1001
                 )

SELECT  PAT_ENC_CSN_ID 'CSN',
        ADMISSION_PROV_ID 'Provider ID'

FROM PAT_ENC_HSP

WHERE PAT_ENC_HSP.ADMISSION_PROV_ID IN (Not_Good.PROV_ID)

But I'm getting a syntax error in the final WHERE clause: The multi-part identifier "Not_Good.PROV_ID" could not be bound.

What is the issue, here?

I don't have any JOIN 's with a missing ON condition, nor do I see an alias missing.

Thanks in advance for your time!

You're very close, but you can't use the CTE in the 'IN' statement in the way you listed above. You can do this, though:

WITH Not_Good AS (  SELECT DISTINCT PROV_ID
                    FROM CL_SER_HIM_LST_VST
                    WHERE HIM_STATUS_C <> 1001
                 )

SELECT  PAT_ENC_CSN_ID 'CSN',
        ADMISSION_PROV_ID 'Provider ID'

FROM PAT_ENC_HSP

WHERE PAT_ENC_HSP.ADMISSION_PROV_ID IN (select PROV_ID from Not_Good)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM