I am struggling to get the data arranged how i would like. Essentially i am aiming to track a containers journey measuring time it spends in locations by looking a the times that it enters and leaves these locations
The table i am pulling from is pictured here

My code is below
INSERT #EXAMTIME SELECT Container_FK ,case when Move_Indicator = '0' then OffChasisTime else null end ,case when Move_Indicator = '1' then OnChasisTime else null end ,case when Move_Indicator = '1' then OffChasisTime else null end ,case when Move_Indicator = '3' then OnChasisTime else null end ,case when Move_Indicator = '3' then OffChasisTime else null end ,case when Move_Indicator = '4' then OnChasisTime else null end FROM #EXTRACT
As you can see the data is each on its own row, I want to group by Container_FK so that each Entry has the whole journey
Many Thanks
Advertisement
Answer
Use aggregation:
select Container_FK,
max(case when Move_Indicator = '0' then OffChasisTime else null end),
max(case when Move_Indicator = '1' then OnChasisTime else null end),
max(case when Move_Indicator = '1' then OffChasisTime else null end),
max(case when Move_Indicator = '3' then OnChasisTime else null end),
max(case when Move_Indicator = '3' then OffChasisTime else null end),
max(case when Move_Indicator = '4' then OnChasisTime else null end)
from #EXTRACT
group by Container_FK;
Note that else null is redundant, so it is just wasted typing. Also, if Move_Indicator is a number, then remove the double quotes around the constants. Numbers should be compared to numbers, not strings.
