小编典典

查询中的字段别名,nzsql

sql

我在Netezza工作,或者您知道的是Analytics(分析)的纯数据-nzsql,但是我认为这是一个ANSI
SQL问题。这个问题是如此基本,我什至不知道如何搜索。

CREATE TEMPORARY TABLE DEMO1 AS SELECT 'SMORK' AS SMORK, 'PLONK' AS PLONK, 'SPROING' AS SPROING;

SELECT SMORK AS PLONK, PLONK, SPROING AS CLUNK, CLUNK
FROM DEMO1;

这将返回“
SMORK,PLONK,SPROING,SPROING”,也就是说,重用CLUNK别名可以很好地进行查询,但是源表中的列会覆盖PLONK别名。现在,如果我真的想要源表中的列,则可以编写SELECT
SMORK AS PLONK,DEMO1.PLONK等,但是我不知道如何指定我更喜欢先前在同一目录中定义的别名。 SELECT子句。

有人知道吗?


阅读 239

收藏
2021-04-07

共1个答案

小编典典

在Netezza中,选择列时, Netezza将首先搜索表列,然后搜索别名。

示例:假设我们有以下语句:

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;

它将返回

**EMPLOYEE_ID FIRST_NAME LAST_NAME FULL_NAME说明**
   1001 Alex Smith Smith,Alex我的全名是:Alex J. Smith

注意,在 DESCRIPTION中 ,FULL_NAME值是从表列而不是别名中选择的。

如果要使DESCRIPTION列使用别名“ FULL_NAME”中的值,则可以分两个步骤进行操作:

步骤1. 创建一个包含所有想要的列的子查询。对于要重用的所有别名,您需要将其命名为FROM子句中任何表列中都不存在的名称。

步骤2. 仅从子查询中选择所需的列。

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;

这将返回您想要的:

**EMPLOYEE_ID FIRST_NAME LAST_NAME FULL_NAME说明**
   1001 Alex Smith Smith,Alex我的全名是:Smith,Alex
2021-04-07