我有这样的表
我从连续日期中得到了不同,但我想计算每次从1开始的日期差异,比如(1-2和1-3再次1-4)
ChildID ID Date
1 4 2005-12-07 00:00:00.000
1 3 2005-11-07 00:00:00.000
1 2 2005-10-09 00:00:00.000
1 1 2005-04-09 00:00:00.000
预期
ChildID ID Date Difference
1 4 2005-12-07 00:00:00.000 243 days (1-4)
1 3 2005-11-07 00:00:00.000 207 days (1-3)
1 2 2005-10-09 00:00:00.000 183 days (1-2)
1 1 2005-04-09 00:00:00.000 NULL
答案 0 :(得分:1)
您可以通过简单查询
来完成declare @temp table(childId int, id int, date datetime)
insert into @temp values(1,4,'2005-12-07 00:00:00.000')
insert into @temp values(1,3,'2005-11-07 00:00:00.000')
insert into @temp values(1,2,' 2005-10-09 00:00:00.000')
insert into @temp values(1,1,'2005-04-09 00:00:00.000')
SELECT t1.*, datediff(day, t2.date, t1.date) AS DateDifference
FROM @temp AS t1
INNER JOIN @temp AS t2 ON t1.childId = t2.id
更新:添加完整示例
1 4 2005-12-07 00:00:00.000 242
1 3 2005-11-07 00:00:00.000 212
1 2 2005-10-09 00:00:00.000 183
1 1 2005-04-09 00:00:00.000 0
结果
await result
答案 1 :(得分:0)
使用窗口函数获取此记录的child_id的最早日期:
SELECT datediff(day, min(date_field) OVER (PARTITION BY child_id) - date_field), child_id, id FROM your_table
这没有考虑到child_id的min(date)可能不是id=1
的记录。因此,如果这是一个问题,那么子查询解决方案:
SELECT datediff(day, t2.datefield, t1.date_field), child_id, id
FROM your_table t1
JOIN (SELECT child_id, date_field FROM your_table where id = 1) t2
ON t1.child_id = t2.child_id;
答案 2 :(得分:0)
1)SQL2012:
SELECT DATEDIFF(DAY, FIRST_VALUE(DATECOL) OVER(ORDER BY ID), DATECOL) AS DIFF ...
FROM ...
2) If ID column has unique values:
SELECT DATEDIFF(DAY, (SELECT A.DATECOL FROM TABLE1 A WHERE A.ID=1), B.DATECOL) AS DIFF ...
FROM TABLE1 B ...
答案 3 :(得分:0)
包含其他样本数据
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard !(annotation is MKUserLocation) else {
return nil
}
if #available(iOS 11.0, *) {
let annoView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: "HunterAnno")
annoView.canShowCallout = true
return annoView
}
let annoView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "HunterAnnoLow")
annoView.canShowCallout = true
return annoView
}
输出
如果您希望最终列看起来像这样
DECLARE @tab TABLE (ChildId INT, Id INT, Date DATETIME)
INSERT INTO @tab
(ChildId, Id, Date)
SELECT 1,4,'2005-12-07 00:00:00.000'
UNION
SELECT 1,3,'2005-11-07 00:00:00.000'
UNION
SELECT 1,2,'2005-10-09 00:00:00.000'
UNION
SELECT 1,1,'2005-04-09 00:00:00.000'
UNION
SELECT 2,1,'2005-12-09 00:00:00.000'
UNION
SELECT 2,2,'2005-12-15 00:00:00.000'
UNION
SELECT 2,3,'2005-12-31 00:00:00.000'
;WITH cteX
AS(
SELECT
T.ChildId
, T.Id
, T.Date
, Diff = DATEDIFF(DAY, MIN(T.Date) OVER ( PARTITION BY T.ChildId), T.Date)
FROM @tab T
)
SELECT
X.ChildId
, X.Id
, X.Date
, Diff = CASE WHEN X.Diff = 0 THEN NULL ELSE X.Diff END
FROM cteX X
ORDER BY
X.ChildId , id DESC
然后像这样修改242 days (1-4)
Diff