我在 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
结果如下:
periodStart mode Volume
0 pt 19
1 pt 24
2 pt 24
3 car 4
3 pt 25
4 car 64
4 pt 27
我需要的看起来像这样-foreach 周期(行)我对每种模式的聚合量(列)感兴趣:
PeriodStart car pt
0 19
1 24
2 24
3 4 25
4 64 27
这如何通过 MSSQL 2012 中的 Pivot 函数来完成?是否可以动态获取列(模式)而不是在查询本身中定义它们?