【发布时间】:2013-12-05 13:08:13
【问题描述】:
我正在尝试编写一个 SQL 查询(使用 ADO 从 Excel 查询 Access)以返回每个不同的 UserID 以及 EventID=916 的 最旧日期和 最早 > 在 916 事件之后此用户发生的 EventID=944 的日期。此外,我想计算日期之间的天数。
测试数据如下:
create table table_name
(
EventID int,
UserId int,
MsgVar1 varchar(4),
MsgVar2 varchar(4),
EventDate date
);
insert into table_name (EventId,UserId,MsgVar1,MsgVar2,EventDate) values
(916,123456,'x', 'x','20110920'),
(944,123456,'x','x','20110923'),
(945,123456,'x','x','20110925'),
(916,123456,'x', 'x','20110928'),
(944,123456,'x', 'x','20110928'),
(916,123458,'x', 'x','20110919'),
(944,123458,'x','x','20110928');
查询应该返回如下:
UserId | Event916Date | Event944Date | Duration
-----------------------------------------------
123456 | 20110920 | 20110923 | 3
123458 | 20110919 | 20110928 | 9
我的出发点如下,但是现在这会返回 所有 944 个事件,而不仅仅是最旧的。
select start.UserID, start.EventDate start, end.EventDate end, datediff(end.EventDate, start.EventDate) duration
from (
select *, (
select UserID from table_name L2 where L2.EventDate>L1.EventDate and L2.UserId=L1.UserId order by EventDate limit 1
) stop_id from table_name L1
) start
join table_name end on end.UserID=start.stop_id
where start.EventID=916 and end.EventID=944;
【问题讨论】:
标签: sql date ms-access ado duration