繁体   English   中英

使用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

演示小提琴

您可以使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM