我有一张这样的表:
| Time | Cash | Employee |
|----------------|----------|
| 03:30 | 300 | McClane |
| 03:35 | 400 | Travis |
| 04:30 | 200 | Travis |
| 04:53 | 100 | John |
我需要选择2个连续的值:
应该是这样的:
| Time | Cash | Employee |
|----------------|----------|
| 03:35 | 400 | Travis |
| 04:30 | 200 | Travis |
我所取得的最接近的是这样的事情:
select time, cash, employee from table where (Cash + Cash) >= 500
和
select time(now() - interval 1 minute)
这可以给我-1分钟,但我不能使用“时间”字段而不是“现在()”功能。
提前感谢您的帮助,并为破碎的英语感到抱歉。
修改 一个很大的错误,如果记录不是连续的并不重要,所以我可以先按时间点它们。
我需要打印这样的记录:
| Time | Cash | Employee |
|----------------|----------|
| 03:35 | 400 | Travis |
| 04:30 | 200 | Travis |
| Time | Cash | Employee |
|----------------|----------|
| 05:00 | 300 | John |
| 05:30 | 300 | John |
| Time | Cash | Employee |
|----------------|----------|
| 06:35 | 200 | McClane |
| 06:37 | 200 | McClane |
| 06:41 | 200 | McClane |
感谢大家的回复,我正在尝试你的答案。
答案 0 :(得分:0)
假设pk
表示表格的PK列:
select s1.pk
, s2.pk
from (
select pk
, employee
, time
, @curRank1 := @curRank1 + 1 AS rank
from table t1
, (SELECT @curRank1 := 2) r1
order by t1.time desc
) s1
inner join (
select pk
, employee
, time
, @curRank2 := @curRank2 + 1 AS rank
from table t2
, (SELECT @curRank2 := 1) r2
order by t2.time desc
) s2
on ( s2.rank = s1.rank
and s2.employee = s1.employee
)
where s1.cash + s2.cash >= 500
and s1.time - s2.time < interval 1 minute
;
答案 1 :(得分:0)
SELECT tc1.ts, tc1.cash, tc1.employee,
TIME_TO_SEC(TIMEDIFF(CONCAT("00:",tc1.ts), CONCAT("00:",tc2.ts))) AS tdiff
FROM time_cash AS tc1 INNER JOIN time_cash tc2 ON tc1.employee = tc2.employee
WHERE tc1.ts <> tc2.ts
AND ABS(TIME_TO_SEC(TIMEDIFF(
CONCAT("00:",tc1.ts), CONCAT("00:",tc2.ts)))) <= 60
AND tc1.cash+tc2.cash > 500
ORDER BY tc1.ts, tc1.employee;
我为此做了sqlfiddle。
我不确定这是否是你需要的。我看到很多可能会改进这一点,但现在你可以开始玩了。
有些问题:
答案 2 :(得分:0)
我们的想法是,您希望在另一个事件发生后的一分钟内为所有事件添加现金金额。您可以使用连接语法执行此操作。我认为相关子查询更清晰:
select t.*
from (select t.*,
(select SUM(cash)
from t t2
where t2.employee = t.employee and
t2.time >= t.time and
t2.time <= t.time + interval 1 minute
) as sumcash
from t
) t
where sumcash >= 500
MySQL中的性能可能不太好。您可以通过索引t(employee, time, cash)
来提高性能。