【问题标题】:Bring next value after condition在条件之后带来下一个值
【发布时间】:2022-01-10 06:06:12
【问题描述】:

我试图在找到条件后获取下一个值。在这种情况下,它是 2021 年 5 月 13 日的一行,我想看到的结果是 2021 年 5 月 19 日的行 Cte 和 CTE1 带来正确的结果。 我不知道我的查询出了什么问题。

<with cte as
(
select
customerid
,max(timestamp) as [Case Submitted]
,row_number() over (partition by [CustomerId] order by [CustomerId] ,max([timestamp]) desc) as rownum
   from Table1
      where substatus = 'Case Submitted'
         and timestamp > '2021-01-01'
Group by 
customerid
,timestamp
)
,CTE2 as
(
Select *
   from cte
     Where rownum = 1
),
CTE3 as
(
select
PS.customerid
,(PS.timestamp) as [Customer Support]
,row_number() over (partition by PS.customerid order by PS.customerid ) as rownum

  from Table1 PS
left join CTE2 C2 on C2.customerid = PS.customerid and C2.[Case Submitted] > PS.timestamp and C2.rownum =1

where status = 'Customer Support'
and timestamp > '2021-01-01'
Group by 
PS.customerid
,ps.timestamp
)
Select*
from CTE3>

【问题讨论】:

  • 在第一个cte中,如果你也按timestamp分组,那么max timestamp只能是分组的timestamp。另外,(partition by col order by col) 毫无意义。
  • 如果您提供查询以创建表并插入示例数据,那么我们将能够检查您的查询,并可能提供我们测试过的更好的解决方案。请提供DDL+DML
  • 请阅读this,了解一些改进问题的技巧。也许您可以解释什么是“条件”以及如何识别“下一个”值。所有列的数据类型是pixel吗?

标签: sql tsql


【解决方案1】:

未经测试的记事本涂鸦

with CTE1 as
(

    select
      customerid
    , [timestamp] as [Case Submitted]
    , rownum = row_number() over (partition by CustomerId order by [timestamp] desc)
    from Table1
    where substatus = 'Case Submitted'
      and [timestamp] > cast('2021-01-01' as date)
), 
CTE2 AS
(
    select
      PS.customerid
    , PS.timestamp as [Customer Support]
    , rownum = row_number() over (partition by PS.customerid order by PS.timestamp)
    from Table1 as PS
    join CTE1 as C1 
      on C1.customerid = PS.customerid 
     and C1.[Case Submitted] > PS.[timestamp] 
     and C1.rownum = 1
    where PS.status = 'Customer Support'
      and [timestamp] > cast('2021-01-01' as date)
)
select * 
from CTE2
where rownum = 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多