SQL Server:使用ROW_NUMBER和CASE语句选择行

时间:2019-05-19 09:22:49

标签: sql sql-server sql-order-by case row-number

我得到了一个子表数据,如下所示:

Id  Cust_id Item_Id  Inactivated_On       Updated_on           Ans
-----------------------------------------------------------------------
15    123     541    2014-05-18 08:44:00  2014-05-18 08:44:00  true
16    123     541    2014-05-18 08:44:00  2014-05-18 08:44:00  123
11    123     541    NULL                 2014-05-18 08:44:00  NULL
12    123     541    2014-05-18 08:44:00  2014-05-18 08:44:00  NULL
13    123     541    2014-05-18 08:44:00  2014-05-18 08:44:00  false
6     123     541    NULL                 2014-05-18 08:44:00  NULL
7     123     541    NULL                 2014-05-18 08:44:00  NULL
15    123     541    NULL                 2014-05-18 08:44:00  false

和父表如下:

Id   Parent_Id   Type_Id
-------------------------
15    NULL        1
16    15          2
11    NULL        2
12    11          2
13    11          1
 6     NULL        2
 7     6           2

现在,我正在尝试基于Updated_on DESC仅获得Inactivated_On子ID(16、12、13、7)排在前1位,因为有重复的ID。结果还应该检查

  • 情况1:如果父Id的Type_Id = 2,则Inactivated_On为NULL
  • 情况2:当父Id的Type_Id = 1时,则Inactivated_On为NULL,并且给定的数据不应将父Ans值设置为'false'
  • 情况3:如果子行和父行Inactivated_On为NULL,则从最终结果集中排除

我最终的预期结果应该是:

 Id  Cust_id Item_Id  Inactivated_On       Updated_on           Ans
 -------------------------------------------------------------------
 12    123     541    2014-05-18 08:44:00  2014-05-18 08:44:00  NULL
 13    123     541    2014-05-18 08:44:00  2014-05-18 08:44:00  false

我尝试过的查询是:

 SELECT 
     CH.Id,
     CH.Cust_id, 
     CH.Item_Id,  
     CH.Inactivated_On,       
     CH.Updated_on,           
     CH.Ans,
     CH.RN
     (SELECT 
          ROW_NUMBER() OVER (PARTITION BY CT.Item_Id, CT.Id ORDER BY CT.Updated_on DESC) AS RN,
          CT.Id,
          CT.Cust_id, 
          CT.Item_Id,  
          CT.Inactivated_On,       
          CT.Updated_on,           
          CT.Ans
      FROM 
          CHILD_TBL AS CT
      INNER JOIN 
          PARENT_TBL AS PT ON PT.Id = CT.Id
      WHERE 
          PT.Parent_Id IS NULL
          CT.Inactivated_On IS NOT NULL -- FOR CASE 3 FILTERING
          AND CT.Cust_id = 123
          AND CT.Item_Id = 541) AS CH
WHERE 
    CH.RN = 1

我正在寻找一个查询,以使案例1和案例2运行正常。非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

从分区中删除ct.id,并将ct.cust_id放入具有item_order的分区中

SELECT CH.Id,
  CH.Cust_id, 
  CH.Item_Id,  
  CH.Inactivated_On,       
  CH.Updated_on,           
  CH.Ans
  (SELECT ROW_NUMBER() OVER (PARTITION BY CT.Item_Id, CT.cust_id ORDER BY 
   CT.Updated_on DESC) AS RN,
   CT.Id,
   CT.Cust_id, 
   CT.Item_Id,  
   CT.Inactivated_On,       
   CT.Updated_on,           
   CT.Ans
   FROM CHILD_TBL AS CT
   INNER JOIN PARENT_TBL AS PT ON PT.Id = CT.Id
   WHERE PT.Parent_Id IS NULL
   AND CT.Cust_id = 123
    AND CT.Item_Id = 541
   ) AS CHLD
  WHERE CH.RN = 1