如何在子查询中引用计算字段?

时间:2014-09-26 13:51:43

标签: tsql correlated-subquery

我有以下查询无效,但显示了我打算做的事情:

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 

以下是样本数据表:

表:工作

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

表:job_event

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

表:bom_item

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

预期结果

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

现在,查询无法编译,因为SQLServer抱怨WOID字段不可用。

有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:2)

您无法在子查询中引用计算字段或别名...

你必须在子查询中再次计算它或在CTE中定义它然后在CTE之外重新使用它

有一篇关于这个主题的有趣文章可能对你很有意思

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