WITH x AS
(
SELECT *,
rn = ROW_NUMBER() OVER (PARTITION BY PersonRFID ORDER BY DateStamp)
FROM AISDb
where action = 'IN'
) ,
y As
(
SELECT *,
rna = ROW_NUMBER() OVER (PARTITION BY PersonRFID ORDER BY DateStamp)
FROM AISDb
where action='OUT'
)
SELECT y.ID,x.ID,x.PersonName,y.PersonName,x.PersonRFID, DATEDIFF(MINUTE, x.TimeStamp, y.TimeStamp)
FROM x , y
where x.PersonRFID = y.PersonRFID
And x.rn=y.rna
AND cast(x.Datestamp as date) = cast(y.Datestamp as date)
Order By x.PersonName;
当我执行上述查询时,我得到下表:
Datestamp personName ID TimeDifference
1/30/2013 Aman Ullah Khan E2001026770D01432810029D 11
1/30/2013 Aman Ullah Khan E2001026770D01432810029D 0
1/30/2013 Aman Ullah Khan E2001026770D01432810029D 1
1/30/2013 Amjad Ali Anjum E2001026770D024125401476 0
1/30/2013 Amjad Ali Anjum E2001026770D024125401476 1
2/9/2013 Amjad Ali Anjum E2001026770D024125401476 31
2/10/2013 Amjad Ali Anjum E2001026770D024125401476 3
2/10/2013 Amjad Ali Anjum E2001026770D024125401476 0
2/10/2013 Amjad Ali Anjum E2001026770D024125401476 3
1/30/2013 Arif Shah E2001026770D01852370206D 0
3/13/2013 Asmat Ullah E2001026770D007624101DA1 456
3/20/2013 Asmat Ullah E2001026770D007624101DA1 558
正如你所看到的,例如人名“amanullah khan”有3个相同日期的记录,即2013年1月30日,但我需要一个记录,如果日期相同,我会得到'时差'
1/30/2013 Aman Ullah Khan E2001026770D01432810029D 14
答案 0 :(得分:1)
试试这个 -
SELECT y.ID ,
x.ID ,
x.PersonName ,
y.PersonName ,
x.PersonRFID ,
SUM(DATEDIFF(MINUTE, x.TimeStamp, y.TimeStamp))
FROM x
JOIN y ON x.PersonRFID = y.PersonRFID
AND x.rn = y.rna
AND CAST(x.Datestamp AS DATE) = CAST(y.Datestamp AS DATE)
GROUP BY y.ID ,
x.ID ,
x.PersonName ,
y.PersonName ,
x.PersonRFID
ORDER BY x.PersonName
答案 1 :(得分:0)
您需要更改如下
SELECT y.ID,x.ID,x.PersonName,y.PersonName,x.PersonRFID,sum(DATEDIFF(MINUTE, x.TimeStamp, y.TimeStamp))
FROM x , y
where x.PersonRFID = y.PersonRFID
And x.rn=y.rna
AND cast(x.Datestamp as date) = cast(y.Datestamp as date)
group by
y.ID,x.ID,x.PersonName,y.PersonName,x.PersonRFID
Order By x.PersonName;