Search code examples
t-sqlcorrelated-subquery

How can I reference a calculated field in a subquery?


I have the following query that is not valid but shows what I intend to do:

SELECT
    REPLACE(j.wo_id, 'PREFIX.', '') AS WOID,
    j.act_finish_time_local,
    STUFF ((SELECT ', '+item_id FROM bom_item WHERE parent_item_id = WOID AND bom_pos > 0 FOR XML PATH('')), 1, 1, '') AS Families
FROM job AS j
INNER JOIN job_event je ON je.wo_id = j.wo_id AND je.oper_id = j.oper_id 
WHERE j.oper_id = 'Sawing' AND j.wo_id LIKE 'PREFIX.%' AND j.act_finish_time_local IS NOT NULL 
GROUP BY j.wo_id, j.act_finish_time_local 
ORDER BY j.act_finish_time_local 

Here's sample data tables:

Table: job

| wo_id       | act_finish_time_local | oper_id |
|-------------|-----------------------|---------|
| PREFIX.0001 | 2014/01/01            | Sawing  |
| PREFIX.0002 | 2014/01/01            | Sawing  |

Table: job_event

| wo_id       | oper_id |
|-------------|---------|
| PREFIX.0001 | Sawing  |
| PREFIX.0002 | Sawing  |

Table: bom_item

| parent_item_id | item_id | bom_pos |
|----------------|---------|---------|
| 0001           | abc     | 1       |
| 0001           | def     | 2       |
| 0002           | qrs     | 1       |
| 0002           | tuv     | 2       |

Expected result

| WOID | act_finish_time_local | Families |
|------|-----------------------|----------|
| 0001 | 2014/01/01            | abc, def |
| 0002 | 2014/01/01            | qrs, tuv |

Now, the query does not compile as SQLServer is complaining about the WOID field not available.

Is there a way to fix this?


Solution

  • You cannot reference a calculated field or an alias in a subquery...

    you have to calculate it again in the subquery or define it in a CTE and then re-use it outside the CTE

    There is an interesting article about this topic which might be interesting for you

    http://joecelkothesqlapprentice.blogspot.ch/2006/06/reference-alias-field-name.html