[英]How to count occurrences using last row value in MySQL
I've written the following query to get the number of times the code field equals the last code field. 我编写了以下查询,以获取代码字段等于最后一个代码字段的次数。 At the same time, I am a complete newbie to this type of syntax (Using Variables) in MySQL. 同时,我是MySQL中这种语法(使用变量)的完全新手。
select
@lastCode:= ts.code as lastCode,
@count:= 0 as count,
ts.id,
ts.date,
ts.code,
if( @lastShiftCode = ts.shift_code, @count := @count + 1, @count:= 0) as occurences
from
empCodes ts
WHERE
ts.date between '2018-01-01' and '2018-02-01'
order by
ts.id,
ts.date
The query runs, but the count never changes from 0 and neither the occurrences changes from 1. I would expect the occurrences to go up by one each row. 查询运行,但计数从0不变,也没有出现从1改变。我希望出现的次数每行增加一。
Here is part of the output 这是输出的一部分
lastCode count id date code occurrences
XX1 0 2 01/02/2018 XX1 1
XX1 0 2 02/02/2018 XX1 1
XX1 0 2 05/02/2018 XX1 1
XX1 0 2 06/02/2018 XX1 1
XX1 0 2 07/02/2018 XX1 1
XX1 0 2 08/02/2018 XX1 1
XX1 0 2 09/02/2018 XX1 1
Try this: 尝试这个:
SELECT ts.id, ts.date, SUM(ts.lastCode=ts.code) `count`
FROM empCodes ts
WHERE ts.date BETWEEN STR_TO_DATE('2018-01-01','%Y-%m-%d')
AND STR_TO_DATE('2018-02-01','%Y-%m-%d')
GROUP BY ts.id, ts.date;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.