Skip to content Skip to sidebar Skip to footer

Db2 As/400 Iseries Use Alias In Where Clause

I'm trying to use the alias of a column in the where clause. for example: SELECT col1 AS alias1, col2 + col3 as sums FROM my_table WHERE sums > 10 But then I get an error mess

Solution 1:

If you really want to use alias in WHERE, not the column itself, you can do it with derived table :

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'
....

Solution 2:

The where-clause is processed before the select-clause in a statement:

The WHERE clause specifies an intermediate result table that consists of those rows of R for which the search-condition is true. R is the result of the FROM clause of the statement.

Re-write the where-clause to reference the actual column name:

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

A common-table-expression can be used to pre-process the select-clause. For example:

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

The columns in a CTE can also be renamed by listing them after the table-identifier. For example:

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'FETCHFIRST1000ROWSONLY

Post a Comment for "Db2 As/400 Iseries Use Alias In Where Clause"