MS SQL Server имеет PIVOT для таких действий.
И CASE можно использовать для группировки этих имен в виде кодов.
Пример фрагмента:
--
-- Using a table variable for easy testing in the example
--
declare @Count_data table (id int identity(1,1) primary key, ATRSTUDY varchar(1), ENDTIME datetime, NAME varchar(30), [COUNT] int);
insert into @Count_data (ATRSTUDY, ENDTIME, NAME, [COUNT]) values
('A','2018-01-01T18:00:15','NorthBound',10),
('A','2018-01-01T18:00:15','SouthBound',20),
('A','2018-01-01T18:00:15','Both Directions',30),
('B','2018-01-01T18:00:15','EastBound',30),
('B','2018-01-01T18:00:15','WestBound',40),
('B','2018-01-01T18:00:15','Both Directions',70);
select ATRSTUDY, ENDDATE, ENDTIME, [C1], [C2], [TC]
from (
select
d.ATRSTUDY,
cast(d.ENDTIME as date) as ENDDATE,
left(cast(d.ENDTIME as time),5) as ENDTIME,
(case -- if the Name column has a Case-Insensitive collation then lower or upper case won't matter.
when d.Name in ('eastbound', 'northbound', 'first direction') then 'C1'
when d.Name in ('westbound', 'southbound', 'second direction') then 'C2'
when d.Name like 'both dir%' then 'TC'
else d.Name
end) as ColName,
d.[count]
From @Count_data d
) as q
pivot (
sum([count])
for ColName in ([C1], [C2], [TC])
) as pvt
order by ATRSTUDY, ENDDATE, ENDTIME;
Выход:
ATRSTUDY ENDDATE ENDTIME C1 C2 TC
-------- ---------- ------- -- -- --
A 2018-01-01 18:00 10 20 30
B 2018-01-01 18:00 30 40 70