I'm using the following query in MSSQL 2012:
declare @startTime int=0*3600;
declare @endTime int=30*3600;
declare @link varchar(10)='RO2566a';
declare @period int=3600;
SELECT (B.time-@startTime)/@period as periodStart, B.link, B.mode, count(*) as Volume
FROM
(
Select A.*,
case when A.vehicle='' then 'walk'
when A.line is NULL then 'car'
else 'pt' end mode
FROM
(Select E.time, E.link, E.vehicle, E.person, T.transitLineId as line, T.transitRouteId as route, T.departureId, T.time as DepartureTime
FROM (Select * From evtEnteredLink where link=@link and time between @startTime and @endTime) E
LEFT OUTER JOIN evtTransitDriverStarts T on (E.vehicle=T.vehicleId)
) A
where A.time between @startTime and @endTime
)B
group by B.link, B.mode, (B.time-@startTime)/@period
The result is as follows:
periodStart mode Volume
0 pt 19
1 pt 24
2 pt 24
3 car 4
3 pt 25
4 car 64
4 pt 27
What I need looks like this - foreach period (rows) I'm interested in the aggregated volumes per mode (column):
PeriodStart car pt
0 19
1 24
2 24
3 4 25
4 64 27
How can this be accomplished via the Pivot function in MSSQL 2012? Is it possible to get the columns (modes) dynamically and not to define them in the query itself?