SQL查询在特定部分修复后查找最多3个事务

时间:2017-04-05 19:49:38

标签: sql teradata

我的数据与此示例类似,非常庞大,因此理想情况下需要高效的代码。我想在充电器维修后找到那些交易(最多3个)。

TRANSACTION_ID  REPAIR_DATE CUSTOMER_ID    COMPONENT   LABOR_CODE_DESC ....
28289           6/25/2015   AH123        LAPTOP       CHARGER REPAIR
28235           6/29/2015    AH123       LAPTOP         CHIP REPLACE
258978         6/27/2013      HW687      PHONE      TOUCH SCREEN
28223           6/2/2014     AH123       LAPTOP      BATTERY REPAIR
215678          9/7/2014       HW687      PHONE         SIM REPAIR
527808          7/30/2016      HW687      LAPTOP         BATTERY REPAIR
567976          7/28/2014      HW687      LAPTOP         CHARGER REPAIR
7678698         8/68/2015     AH123        LAPTOP        BATTERY REPAIR
9987908          5/7/2006       TU890       PHONE         SIM REPAIR
.....


OUTPUT
TRANSACTION_ID  REPAIR_DATE CUSTOMER_ID COMPONENT    LABOR_CODE_DESC ....
28235           6/29/2015    AH123       LAPTOP         CHIP REPLACE
7678698         8/68/2015      AH123        LAPTOP        BATTERY REPAIR
527808          7/30/2016     HW687      LAPTOP          BATTERY REPAIR
215678          9/7/2014       HW687      PHONE     SIM REPAIR

.....

所以我想要的是那些在充电器维修日期之后有充电器维修和最多3笔交易的客户ID交易

SELECT TRANSACTION_ID, REPAIR_DATE,CUSTOMER_ID,LABOR_CODE_DESC from table 
where customer_id IN (SELECT CUSTOMER_ID from table where LABOR_CODE_DESC 
like '%CHARGER REPAIR%')

不确定如何扩展以在CHARGER REPAIR

之后获得最多3笔交易

2 个答案:

答案 0 :(得分:2)

在充电器维修日期之后返回三行:

SELECT *
FROM tab
QUALIFY 
   -- check if any of the three previous rows contains 'CHARGER REPAIR'
   Max(CASE WHEN LABOR_CODE_DESC = 'CHARGER REPAIR' THEN 1 ELSE 0 END)
   Over (PARTITION BY CUSTOMER_ID
         ORDER BY REPAIR_DATE
         ROWS BETWEEN 3 Preceding AND 1 Preceding) = 1

编辑:

仅获取在接下来的10天内具有修复日期的行:

   -- check if any of the previous rows contains 'CHARGER REPAIR'
   -- and the current REPAIR_DATE is within 10 days after that repair
   Max(CASE WHEN LABOR_CODE_DESC = 'CHARGER REPAIR' THEN REPAIR_DATE END)
   Over (PARTITION BY CUSTOMER_ID
         ORDER BY REPAIR_DATE
         ROWS BETWEEN Unbounded Preceding AND 1 Preceding) >= REPAIR_DATE - 10

答案 1 :(得分:-1)

您可以通过以下方式获得所有此类交易:

select t.*
from table t
where t.repair_date > (select t2.repair_date
                       from table t2
                       where t2.customer_id = t.customer_id and
                             labor_code_desc like '%CHARGER REPAIR%'
                      );

将这个限制为每个客户3个是一个小问题,但你可以使用窗口函数:

select t.*
from (select t.*,
             row_number() over (partition by customer_id order by repair_date) as seqnum
      from (select t.*,
                   max(case when labor_code_desc like '%CHARGER REPAIR%' then repair_date end) over (partition by customer_id) as max_crd
            from table t
           ) t
      where t.repair_date > max_crd
     ) t
where seqnum <= 3;