简体   繁体   中英

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.

    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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM