在Teradata中使用Qualify和Rank

时间:2017-04-26 12:09:15

标签: sql teradata rank dense-rank

我试图获得特定产品在Teradata销售时的最新两个月开始日期。由于产品在多个月内销售,我应该只为每种产品获得最近两个销售月份。

尝试使用Qualify with Dense Rank:

SELECT DISTINCT PRODUCT, MONTH_START_DATE,
       DENSE_RANK() OVER (PARTITION BY PRODUCT ORDER BY MONTH_START_DATE DESC ) AS RNK
FROM  EMP_TABLE 
HERE PRODUCT = 'SOAP'

这将给我与Rank和Product不同的月份。像这样:

+---------+------------------+------+
| Product | Month_start_date | RNK  |
+---------+------------------+------+
| SOAP    | 2016-12-01       | 1    |
| SOAP    | 2016-11-01       | 2    | 
| SOAP    | 2016-10-01       | 3    |
+---------+------------------+------+

但如果我重写代码只获得前2:

SELECT DISTINCT PRODUCT, MONTH_START_DATE
       DENSE_RANK() OVER (PARTITION BY PRODUCT ORDER BY MONTH_START_DATE DESC ) AS RNK
FROM  EMP_TABLE
WHERE PRODUCT = 'SOAP' 
QUALIFY  RNK < 3

我总是只得到最高级别的结果。这是什么原因?解决方案是编写一个子查询但想要了解背后的原因&#39; Qaulify&#39;只给出顶排。

感谢您的帮助。

0 个答案:

没有答案