如何使用过滤 运行 Row_Number()

How to run Row_Number() with filtering

我有一个 table,每个 'Case Number' 有多行。我想为每个案例编号选择一行并将其连接回另一行 table 保持一对一的关系。

选择这一行的条件是:

1) 首先过滤掉每个案例编号的所有行,其中 Stage = Cancelled

2) 如果找到 Stage = 'In Progress' 或 'Paused',请选择该行。 (对于案件编号,只能出现这两个中的一个)

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

我已经创建了一个查询来推送行号并根据最新的 'Stop time' 选择一行,但我无法弄清楚如何添加上述过滤器和 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

假设下面的 Case_Number 出现在下面的 table 中,或者现在的 table 必须与 Case_NumberTable

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
)

从你的问题中很难判断,但我的解释是这样的(我无法访问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