Вы можете использовать pivot следующим образом:
CREATE TABLE #N_Preinscripcion(
ID int primary key,
FechaEnv datetime,
Nombre varchar(100),
Periodo varchar(100)
)
INSERT INTO #N_Preinscripcion
VALUES
(20000, '2015-11-20 11:35:38.000', 'María Fernanda', '2016-01'),
(20001, '2015-11-20 11:52:10.000', 'LINA MARIA', '2016-01'),
(20002, '2015-11-20 15:24:14.000', 'ANA PATRICIA', '2016-02'),
(20003, '2015-11-21 09:35:35.000', 'Catalina', '2016-01'),
(20004, '2015-11-21 09:40:04.000', 'Angélica Liliana', '2016-01'),
(20005, '2015-11-21 13:09:56.000', 'paula andrea', '2016-01'),
(20006, '2015-11-21 17:08:52.000', 'luis orlando', '2016-01'),
(20007, '2015-11-21 18:02:33.000', 'ANGELA PAULINA', '2016-01'),
(20008, '2015-11-22 17:29:46.000', 'angie carolina', '2016-01'),
(20009, '2015-11-22 19:36:18.000', 'Nesly Yurani', '2016-02'),
(20010, '2015-11-22 20:49:32.000', 'jennifer lisbeth', '2016-01')
DECLARE @P varchar(100) = '2016-01'
;WITH pivotData as
(
SELECT
DATEPART(WEEKDAY,[P].[FechaEnv]) as [Day],
DATEPART(HOUR,[P].[FechaEnv]) as [Hour],
ID as [ID]
FROM #N_Preinscripcion [P]
WHERE P.Periodo = @P
)
SELECT CASE
[Day]
When 1 Then 'Sunday'
When 2 Then 'Monday'
When 3 Then 'Tuesday'
When 4 Then 'Wednesday'
When 5 Then 'Thursday'
When 6 Then 'Friday'
When 7 Then 'Saturday'
END AS [Day],
[9],[10],[11],[12],[13],[14],[15],[16],[17],[18], [19], [20]
FROM pivotData
PIVOT(COUNT(ID) for [Hour] in ([9],[10],[11],[12], [13], [14], [15], [16], [17], [18], [19], [20])) as pivoted
DROP TABLE #N_Preinscripcion
Выход
Day 9 10 11 12 13 14 15 16 17 18 19 20
--------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- -----------
Sunday 0 0 0 0 0 0 0 0 1 0 0 1
Friday 0 0 2 0 0 0 0 0 0 0 0 0
Saturday 2 0 0 0 1 0 0 0 1 1 0 0