Adrian Keister
Adrian Keister

Reputation: 1035

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!

Upvotes: 1

Views: 2166

Answers (1)

Eloise Maun
Eloise Maun

Reputation: 78

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)

Upvotes: 5

Related Questions