我正在尝试创建一个包含2个coloumns的视图,一个PatrolID和一个表示巡逻长度的数值(以分钟为单位)。巡逻在TYPE coloumn中标记为已启动,变量为PATROL_STARTED和PATROL_FINISHED。这些时间的时间为OCCURRENCE DATE coloumn,带有时间戳(日期时间)。
我尝试过以下操作,但似乎不想工作:
CREATE VIEW RouteDurations AS
SELECT PatrolID,
DATEDIFF(mi, MAX(CASE WHEN ACTION="PATROL_FINISH" THEN [Occurrence Date] END),
MIN(CASE WHEN ACTION="PATROL_START" THEN [Occurrence Date] END)
) AS Duration
FROM [Data Import] AS t
GROUP BY PatrolID
我不能为我的生活找出原因。有人拿起任何东西吗?
答案 0 :(得分:2)
SQL Server不对字符串使用双引号。试试这个:
SELECT PatrolID,
DATEDIFF(minute,
MIN(CASE WHEN ACTION = 'PATROL_STARTED' THEN [Occurrence Date] END),
MAX(CASE WHEN ACTION = 'PATROL_FINISHED' THEN [Occurrence Date] END)
) AS Duration
FROM [Data Import] AS t
GROUP BY PatrolID;
此外,datediff()
的参数首先是开始日期,然后是结束日期。
答案 1 :(得分:0)
您可能想要自我加入。像这样:
select p1.patrolID,
datediff(mi, p1.[Occurrence Date], p2.[Occurrence Date]) minutes
from [Data Import] p1 join [Data Import] p2
on p1.patrolID = p2.patrolID
and p1.action = 'PATROL_START'
and p2.action = 'PATROL_FINISH'
where p1.patrolID = something