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

时间:2017-07-11 14:28:08

标签: teradata

假设我从表中提取此数据:

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增加时才显示产品。因此,在这种情况下,只显示苹果值,因为它满足两个条件。 我想要的输出就是这些行,对于2016Q4的橙色产品year_quarter没有sales_quantity,对于2017Q1年度的产品'秋葵',sales_quantity(50)小于2016Q4的sales_quantity 67。因此,我想只在满足这两个条件时显示。因此它应该只显示这些。

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

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

1 个答案:

答案 0 :(得分:2)

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中使用年份/季度,更好地计算开始和结束范围。如果你想基于今天动态地做这个,你可以使用

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