[英]How to count occurrences using last row value 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
查詢運行,但計數從0不變,也沒有出現從1改變。我希望出現的次數每行增加一。
這是輸出的一部分
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
嘗試這個:
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.