DB2 AS / 400 iseries在where子句中使用别名

时间:2013-06-23 12:50:28

标签: sql db2 ibm-midrange

我正在尝试在where子句中使用列的别名。例如:

SELECT col1 AS alias1, col2 + col3 as sums 
FROM my_table
WHERE sums > 10

但后来我收到一条错误消息:

  

列总和不在指定的表中。

无论如何我能做到吗?

2 个答案:

答案 0 :(得分:6)

如果你真的想在WHERE中使用别名,而不是列本身,你可以使用派生表来实现:

SELECT a.* 
FROM
(
  SELECT lmITNO AS Item_Number, lmBANO AS Lot, lmSTAS AS Status, 
  lmRORN AS Order_Number 
  FROM MVXJDTA.MILOMA 
) a
WHERE a.Status = 'CCC'
....

答案 1 :(得分:6)

where-clause在语句中的select-clause之前处理:

  

WHERE子句指定一个中间结果表,该表由搜索条件为true的R行组成。 R是语句的FROM子句的结果。

重写 where-clause 以引用实际的列名:

...
WHERE A.lmSTAS = 'CCC'
...

common-table-expression可用于预处理 select-clause 。例如:

WITH A AS (SELECT 
    lmITNO AS Item_Number, 
    lmBANO AS Lot, 
    lmSTAS AS Status, 
    lmRORN AS Order_Number 
FROM MVXJDTA.MILOMA)
SELECT A.* FROM A WHERE A.Status = 'CCC'
FETCH FIRST 1000 ROWS ONLY

CTE 中的列也可以通过在 table-identifier 之后列出来重命名。例如:

WITH A (Item_Number, Lot, Status, Order_Number)
AS (SELECT 
    lmITNO, 
    lmBANO, 
    lmSTAS, 
    lmRORN
FROM MVXJDTA.MILOMA)
SELECT A.* FROM A WHERE A.Status = 'CCC'
FETCH FIRST 1000 ROWS ONLY