почему бы не просто GROUP BY The Case Statement:
EG
select
case
when ta.TA_TimeAndDate BETWEEN DATEADD(minute, -120, pro.GameTime) AND DATEADD(minute, -90, pro.GameTime)
then 'Between -120 mins and -90 mins'
when ta.TA_TimeAndDate BETWEEN DATEADD(minute, -90, pro.GameTime) AND DATEADD(minute, -60, pro.GameTime)
then 'Between -90 mins and -60 mins'
when ta.TA_TimeAndDate BETWEEN DATEADD(minute, -60, pro.GameTime) AND DATEADD(minute, -45, pro.GameTime)
then 'Between -60 mins and -45 mins'
else ''
END
as TimePeriod,
count(*) as Flow
FROM attendance ta
INNER JOIN TA_OperationCode toc
ON ta.TA_OperationCode = toc.OperationCode
LEFT OUTER JOIN SubStations sub
ON TA_ServiceNumber = sub.ServiceNumber
AND TA_DoorNumber = sub.DoorNumber
INNER JOIN [dbo].[Products] pro
ON ta.TA_GameNumber = pro.prd_GameNumber
INNER JOIN dbo.producttypes prot
ON ta.TA_Eventtype = prot.PRD_TypeID AND @EventType = prot.PRD_EventTypeID
WHERE GameNumber = @GameNumber
AND EventType = @EventType
AND ta.TA_TimeAndDate BETWEEN DATEADD(minute, -120, pro.GameTime) AND DATEADD(minute, -45, pro.GameTime)
group by
case
when ta.TA_TimeAndDate BETWEEN DATEADD(minute, -120, pro.GameTime) AND DATEADD(minute, -90, pro.GameTime)
then 'Between -120 mins and -90 mins'
when ta.TA_TimeAndDate BETWEEN DATEADD(minute, -90, pro.GameTime) AND DATEADD(minute, -60, pro.GameTime)
then 'Between -90 mins and -60 mins'
when ta.TA_TimeAndDate BETWEEN DATEADD(minute, -60, pro.GameTime) AND DATEADD(minute, -45, pro.GameTime)
then 'Between -60 mins and -45 mins'
else ''
END
если важна внутренняя разница соединений, вы можете вместо этого добавить ее как левое соединение и проверить, не является ли оно нулевым, в предложении where, например:
AND (toc.OperationCode is not null or ta.TA_TimeAndDate > DATEADD(minute, -90, pro.GameTime))
`