Field Aliasing in queries, nzsql

自古美人都是妖i 提交于 2019-12-01 12:35:38

In Netezza, when selecting a column, Netezza will search for table column first, and then alias.

Example: Suppose we have the following statements:

CREATE TEMPORARY TABLE EMPLOYEES AS 
SELECT 1001 AS EMPLOYEE_ID
      ,'Alex' AS FIRST_NAME
      ,'Smith' AS LAST_NAME
      ,'Alex J. Smith' AS FULL_NAME;

SELECT 
     EMPLOYEE_ID
    ,FIRST_NAME
    ,LAST_NAME
    ,LAST_NAME||', '||FIRST_NAME AS FULL_NAME
    ,'My full name is :'||FULL_NAME AS DESCRIPTION
  FROM EMPLOYEES;

It will return

EMPLOYEE_ID  FIRST_NAME  LAST_NAME   FULL_NAME      DESCRIPTION
   1001        Alex        Smith     Smith, Alex    My full name is :Alex J. Smith

Notice in DESCRIPTION, the FULL_NAME value is picked from table column, not from alias.

If you want DESCRIPTION column use value from alias FULL_NAME, you can do it in two steps:

Step 1. Create a sub-query includes all columns you want. For all alias names you want to reuse, you need to name them as names not exist in any table columns on your FROM clause;

Step 2. SELECT only column you want from the subquery.

CREATE TEMPORARY TABLE EMPLOYEES AS SELECT 1001 AS EMPLOYEE_ID, 'Alex' AS FIRST_NAME, 'Smith' AS LAST_NAME, 'Alex J. Smith' AS FULL_NAME;

WITH EMPLOYESS_TMP AS (
SELECT 
     EMPLOYEE_ID
    ,FIRST_NAME
    ,LAST_NAME
    ,LAST_NAME||', '||FIRST_NAME AS FULL_NAME2
    ,FULL_NAME2 AS FULL_NAME
    ,'My full name is :'||FULL_NAME2 AS DESCRIPTION
  FROM EMPLOYEES)
SELECT 
     EMPLOYEE_ID
    ,FIRST_NAME
    ,LAST_NAME
    ,FULL_NAME
    ,DESCRIPTION
 FROM EMPLOYESS_TMP;   

This will return what you want:

EMPLOYEE_ID  FIRST_NAME  LAST_NAME   FULL_NAME      DESCRIPTION
   1001        Alex        Smith    Smith, Alex     My full name is :Smith, Alex

Just change the order of your columns. Netezza tries to use your alias so you can either rename the column or change the order.

SELECT SMORK AS PLONK, PLONK, CLUNK, SPROING AS CLUNK
FROM DEMO1;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!