Na základě diskusí v chatu pro 3 seskupení, což poskytlo SQLFiddle pro testovací data (tam není mnoho dat).
Kvůli testovacím datům s posuvným oknem kde now() je ve vztahu k těmto datům, byla pro "zmrazení" now() použita následující proměnná . Jednoduše pro usnadnění testování a ověřování výstupu.
Takže to nakonec zavrhněte a změňte 4 odkazy v kódu, které to používají (všimněte si, že skupina 3 to používá dvakrát).
now() proměnná:
select @theNow:=now();
-- REM OUT the following line. It is used only for testing (as now will chg, your data won't)
select @theNow:='2016-06-23 14:00:00';
Dotaz:
select id,sentNum,message,sentTime,startAtTime,sentByTime,msgType,theGrp from
( select id,sentNum,message,sentTime,startAtTime,sentByTime,msgType,theGrp,
if(example@sqldat.com,greatest(@sentNumChg:=1,0),least(@sentNumChg:=0,1)) as dummy1,
if(example@sqldat.com,greatest(@grpChg:=1,0),least(@grpChg:=0,1)) as dummy2,
if(@sentNumChg=1 or @grpChg=1,@seqNum:=1,@seqNum:example@sqldat.com+1) as seqNum,
@lastSentNum:=sentNum as setLast01,
@lastGrp:=theGrp as setLast02
from
( -- GROUP 1: sentByTime<=now(), INVITE
select `id`, `sentNum`, `message`, `sentTime`, `startAtTime`, `sentByTime`, `msgType`, 1 as theGrp
from SmsQueue
where sentByTime<example@sqldat.com and msgType='invite'
UNION ALL
-- GROUP 2 startAtTime<=now(), BROADCAST
select `id`, `sentNum`, `message`, `sentTime`, `startAtTime`, `sentByTime`, `msgType`, 2 as theGrp
from SmsQueue
where startAtTime<example@sqldat.com and msgType='broadcast'
UNION ALL
-- GROUP 3: sentByTime>now() && startAtTime<=now(), INVITE
select `id`, `sentNum`, `message`, `sentTime`, `startAtTime`, `sentByTime`, `msgType`, 3 as theGrp
from SmsQueue
where sentByTime>@theNow and startAtTime<example@sqldat.com and msgType='invite'
) d1
cross join (select @sentNumChg:=0,@grpChg:=0,@lastSentNum:='',@lastGrp:=0,@seqNum:=0) as xParams
order by sentNum,theGrp,sentByTime,id -- id is the tie-break
) d2
where (theGrp=1 and seqNum<3) or (theGrp=2 and seqNum=1) or (theGrp=3 and seqNum=1)
order by sentNum,theGrp;
Výstup (můj klientský nástroj je v tuto chvíli napaden textem):
Viz mé obecné komentáře v horní části toto moje odpověď pro pokročilé použití proměnné.