2

我正在向 IBM DB2 服务器编写以下查询:

SELECT 
    EMPNO, 
    YEAR(CURRENT TIMESTAMP - BIRTHDATE) AS AGE,
    DENSE_RANK() OVER(ORDER BY YEAR(CURRENT TIMESTAMP - BIRTHDATE) ASC) AS RANK

FROM 
    DANDY.EMPLOYEE;

它有效,但看起来很难看,因为我正在重复表达:

YEAR(CURRENT TIMESTAMP - BIRTHDATE)

但是这样写是行不通的:

DENSE_RANK() OVER(ORDER BY AGE ASC) AS RANK

如何让它变得更好?

4

3 回答 3

2
SELECT 
EMPNO, 
AGE,
DENSE_RANK() OVER(ORDER BY AGE ASC) AS RANK
FROM (SELECT EMPNO,
             YEAR(CURRENT TIMESTAMP - BIRTHDATE) AS AGE
      FROM DANDY.EMPLOYEE);
于 2012-12-10T21:00:36.947 回答
0

我知道标准ORDER BY条款通常接受列索引,但不确定它是否适用DENSE_RANK()- 也许尝试:

DENSE_RANK() OVER(ORDER BY 2 ASC) AS RANK
于 2012-12-10T20:56:49.373 回答
0

您可以使用公用表表达式 (CTE) 来获取AGE,然后AGE根据需要再次使用。

WITH
   CTEAGE AS
      (SELECT 
          YEAR(CURRENT TIMESTAMP - BIRTHDATE) AS AGE,
      FROM 
          DANDY.EMPLOYEE
      )

   SELECT 
      EMPNO, 
      CTEAGE.AGE,
      DENSE_RANK() OVER(CTEAGE.AGE ASC) AS RANK
   FROM 
      DANDY.EMPLOYEE;
于 2012-12-10T20:59:49.563 回答