如何通过过滤运行Row_Number()

时间:2019-03-28 09:55:47

标签: sql tsql row-number

我有一个表,其中每个“案例编号”都有多行。我想为每个“个案编号”选择一行,然后将其重新连接到另一个表,保持一对一的关系。

选择此行的条件是:

1)首先,筛选出每个具有Stage = Canceled的个案编号的所有行

2)如果找到Stage =“进行中”或“已暂停”,请选择该行。 (案例编号只能显示这两个中的一个)

3)如果不是(2),则选择Stage ='Completed',但选择最新的'Stop Time'。 (这是我认为我们可能必须使用ROW_NUMBER()的地方)

我已经创建了一个查询来推送行号并根据最新的“停止时间”提取一行,但我不知道如何在其中添加上述过滤器和if-else条件

    SELECT  [Case Number],
ROW_NUMBER ( )  
    OVER ( PARTITION BY [Case Number] order by [Stop time] desc )  idx
      ,[Stage]
      ,[Time left]
      ,[SLA definition]
      ,[Elapsed time]
      ,[Elapsed percentage]
      ,[Start time]
      ,[Stop time]
      ,[Has breached]
      ,[Breach time]
      ,[Updated]
      ,[Updated by]
      ,[Created]
      ,[Created by]


  FROM ( select * from [SLA_Data] where Stage != 'Cancelled' )v1

2 个答案:

答案 0 :(得分:0)

假设下表中存在 Case_Number ,则下面的代码应该可以工作,或者当前表必须与 Case_Number

结合在一起
create view [dbo].[SLA_View] as select * from (

SELECT * FROM
(
SELECT  [Task]
      ,[Stage]
      ,[Time left]
      ,[SLA definition]
      ,[Elapsed time]
      ,[Elapsed percentage]
      ,[Start time]
      ,[Stop time]
      ,[Has breached]
      ,[Breach time]
      ,[Updated]
      ,[Updated by]
      ,[Created]
      ,[Created by]
FROM
(
/* GETS SINGLE CASE FOR MULTIPLE STAGES */
SELECT *,ROW_NUMBER ( )  OVER ( PARTITION BY Task order by [Stage] desc)  RNK
 FROM [SLA_Data] WHERE [CASE_NUMBER] IN 
(
/* GETS DISTINCT CASE NUMBER WITH STAGE = 'PAUSED' OR 'IN PROGRESS' */
SELECT DISTINCT [CASE_NUMBER]
  FROM [SLA_Data]
  WHERE [Stage] != 'Cancelled'
  AND [Stage] IN ('Paused','In Progess')
  GROUP BY  [CASE_NUMBER]
  HAVING COUNT(*) >= 1
  )
  )Y
  WHERE RNK = 1
)Z
UNION
SELECT [Task]
      ,[Stage]
      ,[Time left]
      ,[SLA definition]
      ,[Elapsed time]
      ,[Elapsed percentage]
      ,[Start time]
      ,[Stop time]
      ,[Has breached]
      ,[Breach time]
      ,[Updated]
      ,[Updated by]
      ,[Created]
      ,[Created by]
      FROM
      (
      SELECT *, ROW_NUMBER ( )  OVER ( PARTITION BY Task order by [start time] desc)  idx
      FROM [SLA_Data]
      WHERE [CASE_NUMBER] NOT IN (
      SELECT DISTINCT [CASE_NUMBER]
  FROM [SLA_Data]
  WHERE [Stage] != 'Cancelled'
  AND [Stage] IN ('Paused','In Progess')
  GROUP BY  [CASE_NUMBER]
  HAVING COUNT(*) > 1
  )
)v1 where idx = 1
)

答案 1 :(得分:0)

从您的问题中很难分辨出来,但这是我的解释(我无法访问SQL,也没有提供足够的测试数据,因此无法对其进行测试)

   select * from
    ( 
    SELECT  [Task],...,...,
    ROW_NUMBER ( )      
    OVER ( PARTITION BY Task order by 
        case 
        when Stage in('In Progress' ,'Paused') then 1
        when Stage='Completed' then 2 end,
        [Stop time] desc )  idx
    ) 
    where idx=1