下面的查询有效,但是我想知道是否有更好的方法可以做到这一点。
有一个子查询使用两个子查询。这两个子查询是相同的,但是返回两个不同的字段。有没有一种方法可以只使用一个返回两个字段的子查询?
我检查了类似的问题(this,this和this),但我认为它们不适用于这种情况。
这是查询:
SELECT *,
time(strftime('%s', EndTime) - strftime('%s', StartTime), 'unixepoch') AS Duration
FROM (
SELECT (
SELECT Time
FROM Log AS LogStart
WHERE LogStart.User = Log.User AND
LogStart.Time <= Log.Time AND
LogStart.[Action] != 'done'
ORDER BY LogStart.Time DESC
LIMIT 1
)
AS StartTime,
Time AS EndTime,
User,
(
SELECT [Action]
FROM Log AS LogStart
WHERE LogStart.User = Log.User AND
LogStart.Time <= Log.Time AND
LogStart.[Action] != 'done'
ORDER BY LogStart.Time DESC
LIMIT 1
)
AS [Action]
FROM Log
WHERE [Action] = 'done'
)
ORDER BY duration DESC;
这是一些测试数据:
CREATE TABLE Log (
Time DATETIME,
User CHAR,
[Action] CHAR
);
insert into Log values('2017-01-01 10:00:00', 'Joe', 'Play');
insert into Log values('2017-01-01 10:01:00', 'Joe', 'done');
insert into Log values('2017-01-01 10:02:00', 'Joe', 'Sing');
insert into Log values('2017-01-01 10:03:00', 'Joe', 'done');
insert into Log values('2017-01-01 10:04:00', 'Ann', 'Play');
insert into Log values('2017-01-01 10:04:30', 'Bob', 'Action without corresponding "done" which must be ignored');
insert into Log values('2017-01-01 10:05:00', 'Joe', 'Play');
insert into Log values('2017-01-01 10:06:00', 'Ann', 'done');
insert into Log values('2017-01-01 10:07:00', 'Joe', 'done');
insert into Log values('2017-01-01 10:08:00', 'Ann', 'Play');
insert into Log values('2017-01-01 10:09:00', 'Ann', 'done');
最佳答案
使用自我连接...我没有SQLLite,因此语法可能不在此处,但是您应该明白...
Select e.*, time(strftime('%s', e.[Time]) -
strftime('%s', s.[Time]), 'unixepoch') AS Duration
From log e join log s -- s is for the startevent; e for end event
on s.[User] = e.[User]
and s.[Action] != 'done'
and e.[Action] = 'done'
and s.[Time] =
(Select Max([time] from log
where [User] = e.[User]
and [time] <= e.[Time]
and [Action] != 'done')
关于sql - 如何从子查询返回两个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42766634/