从同一ID中选择多个记录之间的日期差

时间:2019-06-11 18:53:36

标签: sql sql-server

我需要计算两次母亲出生之间经过的月数。 如果母亲只有一个孩子,则此数字应为0。对于双胞胎,该数字也应为0(相同的出生日期)。 我认为这可能有效,但似乎效率很低。什么是这样做的好方法?

CREATE TABLE Births (
MotherID int,
ChildID int,
ChildBDate date,
BirthOrder int
);


INSERT INTO Births (MotherID, ChildID, ChildBDate, BirthOrder)
VALUES ('1234567', '7654321', '1977-01-02', '1'), 
       ('1234567', '6548721', '1981-05-04', '2'), 
       ('1234567', '4548712', '1983-10-19', '3'), 
       ('5587214', '4477441', '1986-07-21', '1'),
       ('4452012', '6782114', '1991-08-22', '1'),
       ('4452012', '8754557', '1991-08-22', '2');

SELECT MotherID,
       ChildID,
       ChildBDate,
       BirthOrder,
       BirthInterval = DATEDIFF(MONTH, a.childbdate, B.childbdate)
FROM Births a
    JOIN Births B
        ON a.motherID = B.motherID
WHERE a.BirthOrder= 1
         AND b.BirthOrder= 2
      OR a.BirthOrder= 2
         AND b.BirthOrder= 3
      OR a.BirthOrder= 3
         AND b.BirthOrder= 4
      OR a.BirthOrder= 4
         AND b.BirthOrder= 5
      OR a.BirthOrder= 1
         AND b.BirthOrder= 1

1 个答案:

答案 0 :(得分:0)

您可以使用聚合:

select motherId,
       coalece(datediff(day, min(childbdate), max(childbdate)) / nullif(count(*) - 1, 0), 0)
from births b
group by motherId;

平均分娩时间是指从最早出生到最近出生之间的时间间隔,除以少于出生数量的数字。

nullif()防止被零除。 coalesce()然后将单身母亲变成0

编辑:

我想我误会了。您似乎想要lag()

select b.*,
       datediff(day, 
                lag(b.childbdate, 1, b.childbdate) over (partition by motherId order by b.birthorder),
                b.childbdate
               ) as birthinterval
from births b;

我不确定这对双胞胎如何工作。

Here是db <>小提琴。

相关问题