Teradata- 仅当满足两个行条件时才显示

Teradata- To display only when two row conditions are satisfied

假设我从 table:

中提取这些数据
Category    Product    Year_Quarter    Sales_Quantity...
Fruit       Apple      2016Q4          300
Fruit       Apple      2017Q1          400
Fruit       Apple      2017Q2          450
Fruit       Orange     2017Q1          45
Fruit       Orange     2017Q2          70
Vegetable   Okra       2016Q4          67
Vegetable   Okra       2017Q1          50
Vegetable   Okra       2017Q2          78....

这是我为提取这种格式而编写的代码

Select Category,Product 
   ,EXTRACT(YEAR from  Date) || 'Q' || TRIM(((CAST(EXTRACT(MONTH FROM Date) AS BYTEINT)-1)/3)+1) as  YEAR_QUARTER
   ,COUNT(DISTINCT Sales) as Sales_Quantity 
from table
where YEAR_QUARTER like any ('%2016Q4','%2017Q1','%2017Q2') 
group by Category,Product,YEAR_QUARTER
order by Category, Product, YEAR_QUARTER

我希望仅当所有三个值 2016Q4、2017Q1、2017Q2 都有一些 sales_quantity 并且 Sales_quantity 随着 year_quarter 增加时才显示产品。所以在这种情况下,只有满足这两个条件的苹果值才会显示。 我想要的输出只是这些行,对于 2016 年第四季度的橙色产品 year_quarter 没有 sales_quantity,对于 2017 年第一季度的产品 'okra',sales_quantity(50) 小于sales_quantity 2016 年第 4 季度为 67。因此,我只想在满足这两个条件时显示。因此它应该只显示这些。

Category    Product    Year_Quarter    Sales_Quantity...
Fruit       Apple      2016Q4          300
Fruit       Apple      2017Q1          400
Fruit       Apple      2017Q2          450

如何在我当前的代码中添加这些条件?

SELECT *
FROM
 (
   SELECT Category
      ,Product
        -- simplified quarter calculation
      ,To_Char(datecol, 'yyyy"Q"q') AS YEAR_QUARTER
        -- do you really need DISTINCT?
      ,Count(DISTINCT Sales) AS Sales_Quantity 
      ,CASE-- check if previous row is lower (or the 1st row)
         WHEN 
           Min(Sales_Quantity)
           Over (PARTITION BY Category,Product
                 ORDER BY YEAR_QUARTER
                 ROWS BETWEEN 1 Preceding AND 1 Preceding) > Sales_Quantity
         THEN 1 --higher
         ELSE 0 --lower or 1st row
       END AS flag
   FROM tab
     -- simplified
   WHERE datecol BETWEEN DATE '2016-10-01' AND DATE '2017-06-30' 
   GROUP BY Category,Product,YEAR_QUARTER
     only those where all 3 quarters exist
   QUALIFY Count(*) Over (PARTITION BY Category,Product) = 3
 ) AS dt
  -- only those rows with increasing sales
QUALIFY Max(flag)
        Over (PARTITION BY Category,Product) = 0

你应该避免在 WHERE 中使用 year/quarter,最好计算开始和结束范围。如果您想根据今天动态地执行此操作,您可以使用

获得最后三个季度
BETWEEN Add_Months(Trunc(Current_Date, 'Q'),-9)
    AND Trunc(Current_Date, 'Q') -1