在一个带有行的表中介绍狗的交配。通常在母体热循环中发生多次交配,因此,具有相同母体且加热时间紧密的交配意味着单个热循环。例如:
Date Female
---------- ---------
2019-03-28 Female1
2019-04-01 Female1
2019-04-03 Female1
2019-10-15 Female2
2019-10-16 Female2
2019-10-19 Female1
2019-10-23 Female1
在表中,您可以看到三个交配组,其中2个代表雌性1,1个代表雌性2。我想选择这些行,然后在结果中添加一列,以标识不同分组的配对关系。分组中的开始日期和结束日期相隔不超过10天。
我尝试将日期字段转换为纪元秒,然后除以某个数字。这给了我一些东西,但是分组中有很多错误。
答案 0 :(得分:0)
WITH cte AS (
SELECT "Date",
"Female",
-- assume that the lag is not more than 7 days
CASE WHEN ("Date" - LAG("Date") OVER (PARTITION BY "Female" ORDER BY "Date")) <= 7
THEN 0
ELSE 1 END "is it mating start?"
FROM matings
)
SELECT "Date",
"Female",
SUM("is it mating start?") OVER (PARTITION BY "Female" ORDER BY "Date") "mating number"
FROM cte
ORDER BY "Female", "Date";