使用 Row_Number 函数

Using the Row_Number function

我的数据是这样的 -

clientid    calendar    Num
18161       20170518    1
18161       20170705    0
18161       20170718    0
43431       20150518    0

18161 客户的第一个 0 Num 在第二个日历上。 43431 客户的第一个 0 Num 在第一个日历 (20150518) 上。我想要一个 SQL 来生成这个输出 -

clientid    FirstZero
18161       2 
43431       1

这是我目前所拥有的,但是正在为所有 calendars 生成 row_number。我第一次需要它 Num 对于特定客户端变为零。

SELECT clientid, calendar,
Row_Number() Over (order by clientid) As FirstZero
from DAILY
where num = 0  
and clientid = 18161

给你:

select
  clientid,
  min(pos) as firstzero
from (
  select
    clientid,
    num,
    row_number() over(partition by clientid order by calendar) as pos
  from daily
) x
where num = 0
group by clientid
with fz as 
(
SELECT clientid, calendar, num, 
Row_Number() Over (partition by clientId order by calendar) As FirstZero
from DAILY
),
gz as
(
  select clientid, min(FirstZero) as FirstZero 
  from fz
  where num = 0
  group by clientId
)
select d.clientId, d.calendar, gz.firstZero
 from Daily d 
 inner join fz on d.clientId = fz.clientId and d.calendar = fz.calendar
 inner join gz on fz.clientId = gz.clientId and fz.firstZero = gz.firstZero
 --where d.clientId = 18161

Demo Fiddle

您可以使用 CTE 生成 row_numbers,然后找到 MIN()

;WITH cte AS (
SELECT clientID, 
Calendar, 
Num, 
ROW_NUMBER() OVER(PARTITION BY clientid ORDER BY calendar) AS counter_
FROM table
)
SELECT 
clientID, MIN(counter_) AS FirstZero
FROM cte 
WHERE Num=0
GROUP BY clientID