使用Row_Number函数

时间:2019-01-29 18:37:47

标签: sql window-functions

我的数据看起来像这样-

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

Num客户端的前0个18161在第二个日历上。 Num客户端的前0个43431在第一个日历(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

3 个答案:

答案 0 :(得分:0)

您在这里:

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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