我的数据看起来像这样-
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
答案 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
答案 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