I have this query:
set @last_uid = 0;
set @last_tm = '00:00';
set @last_vid = 0;
SELECT v.*,
CASE WHEN @last_uid = visitorid AND cast( @last_tm as datetime) >= subtime( timestamp, '01:00' )
THEN
if( (@last_tm := timestamp ), @last_vid, @last_vid)
ELSE
if( (@last_uid := visitorid) + (@last_vid := @last_vid+1) +(@last_tm := timestamp ),@last_vid, @last_vid )
END AS newVisitID
FROM visits v
ORDER BY timestamp DESC, visitorid
I tried to use the newVisitID column in the WHERE clause like this:
WHERE newVisitID <=5
This gives me the error:
#1054 - Unknown column 'newVisitID' in 'where clause'
Could anyone help me solve this?
You can't reference aliases in the WHERE clause, but you can reference them in HAVING:
SELECT v.*,
CASE WHEN @last_uid = visitorid AND cast( @last_tm as datetime) >= subtime( timestamp, '01:00' )
THEN
if( (@last_tm := timestamp ), @last_vid, @last_vid)
ELSE
if( (@last_uid := visitorid) + (@last_vid := @last_vid+1) +(@last_tm := timestamp ),@last_vid, @last_vid )
END AS newVisitID
FROM visits v
HAVING newVisitID <- 5
ORDER BY timestamp DESC, visitorid
You can write out the case statement again, or the easier way is to wrap it and then filter the subquery:
select * from
(
SELECT v.*,
CASE WHEN @last_uid = visitorid AND cast( @last_tm as datetime) >= subtime( timestamp, '01:00' )
THEN if( (@last_tm := timestamp ), @last_vid, @last_vid)
ELSE if( (@last_uid := visitorid) + (@last_vid := @last_vid+1) +(@last_tm := timestamp ),@last_vid, @last_vid )
END AS newVisitID
FROM visits v
) x
WHERE x.newVisitID <= 5
ORDER BY x.timestamp DESC, x.visitorid
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With