当日期值相同时,根据订单对结果进行分组

时间:2015-11-06 09:32:24

标签: sql sql-server

我在CTE中创建了一个基表,然后用于根据业务规则派生类型,然后验证事实表中的输出。 但是,事实表中添加了一条新规则,即当记录具有相同的创建日期时,优先级顺序如下:

  • Entrytypeid = 5,routeId ='Phone',然后是1
  • Entrytypeid in(2,3,4,5)then 2
  • 所有其他Entrytypeid然后3

我的查询将产生如下的基表,然后是获取交互类型:

with CTE_TypeBase as
(

     SELECT 

    th.IncidentId,
    CurrIncidentStatus = inc.incidentstatusid,
    isnull(th.StaffId,-1) as CurrStaffId,
    CurrEntryTypeID  = th.EntryTypeID ,
    CurrDateCreated = th.DateCreated,
    PrevEntryTypeID = lag(th.EntryTypeID , 1,0) OVER (PARTITION BY                  th.IncidentId ORDER BY th.DateCreated asc),
    PrevDateCreated = lag(th.DateCreated, 1,0) OVER (PARTITION BY th.IncidentId ORDER BY th.DateCreated asc),
    PrevID Id = lag(th.ID Id, 1,0) OVER (PARTITION BY th.IncidentId ORDER BY th.DateCreated asc),
    PrevStaffId = isnull(lag(th.StaffId, 1,0) OVER (PARTITION BY th.IncidentId ORDER BY th.DateCreated asc),-1),
    PrevIncidentStatus = lag(inc.IncidentStatusId, 1,0) OVER (PARTITION BY th.IncidentId ORDER BY th.DateCreated asc),
    CurrID Id = th.ID Id,
    PrecedenceOrder = DENSE_RANK() over (partition by th.DateCreated order by th.DateCreated, th.EntryTypeID  asc),
    RowNumber = ROW_NUMBER() OVER (PARTITION BY th.IncidentId ORDER BY th.DateCreated asc)


FROM stage.ID  th
left join [stage].[Incident] inc on inc.IncidentId = th.IncidentId
WHERE th.EntryTypeID  in (2,3,4,5,6,7,8)
  and th.incidentid = 150000)

选择输出:

  IncidentId    CurrEntryTypeId CurrDateCreated    PrevEntryTypeID  PrevDateCreated     PrevId  CurrId  PrecedenceOrder    RowNumber
  150000        3               22/08/2013 13:37    0                  01/01/1900 00:00 0       238475  1                   1
  150000        6               22/08/2013 13:37    3              22/08/2013 13:37 238475  238476  2                   2
  150000        3               22/08/2013 13:58    6               22/08/2013 13:37    238476  239035  1                   3
  150000        2               22/08/2013 18:50    3                 22/08/2013 13:58  239035  248796  1                   4

现在我设法使用dense_rank来识别哪些记录遵循优先级顺序,然后我需要识别那些属于优先级的记录。

我考虑添加另一个CTE然后引用CTE_TypeBase,然后使用case来识别任何具有precedenceOrder>的记录。 1然后设置为1。 但是这只会识别1条记录,我需要能够选择具有相同创建日期的记录并应用相同的逻辑。

所以我需要获得如下输出,忽略其他值并仅返回受影响的值:

  IncidentId    CurrEntryTypeId CurrDateCreated    CurrId   PrecedenceOrder    RowNumber
  150000        3               22/08/2013 13:37   238475   1                   1
  150000        6               22/08/2013 13:37   238476   2                   2

0 个答案:

没有答案