📅  最后修改于: 2022-03-11 15:05:19.052000             🧑  作者: Mango
WITH Partitioned AS( SELECT *, ROW_NUMBER() OVER (PARTITION BY cu_id, date ORDER BY cu_id, date) AS RowNumber FROM @Table) SELECT *, CASE WHEN RowNumber > 1 THEN 0 ELSE COALESCE(DATEDIFF(DAY, (SELECT MAX(date) FROM @Table WHERE date < a.date AND cu_id = a.cu_id), a.date), 0) END AS Days_betweenFROM Partitioned a