Вы можете попробовать следующий подход. Шаги:
- Генерация всех возможных дат в пределах диапазона с использованием рекурсии (или календаря
таблица)
- Получить все комбинации между датами, именами и рассчитанными оставшимися часами
- Данные PIVOT
T-SQL - это статический пример, если вам нужны данные за разные дни, вам нужно сгенерировать динамический оператор:
---------------------------
-- Table
---------------------------
CREATE TABLE #Table (
[Name] varchar(10),
[Date] date,
[Hours] numeric(5, 1)
)
INSERT INTO #Table
(Name, [Date], Hours)
VALUES
('Sam', '2019-01-09', 9),
('Sam', '2019-01-10', 3),
('Sam', '2019-01-10', 4),
('Sam', '2019-01-11', 7),
('Marcos', '2019-01-09', 1),
('Marcos', '2019-01-10', 8),
('Marcos', '2019-01-11', 2),
('Marcos', '2019-01-11', 6.5),
('David', '2019-01-11', 2),
('David', '2019-01-10', 5),
('David', '2019-01-09', 3)
---------------------------
-- Statement
---------------------------
;WITH dates AS (
-- Generate all possible dates within range using recursion
SELECT CONVERT(date, '2019-01-09') AS [Date]
UNION ALL
SELECT DATEADD(day, 1, [Date])
FROM dates
WHERE [Date] < CONVERT(date, '2019-01-12')
)
SELECT
-- Non-pivoted and pivoted columns
[Name],
[2019-01-09] AS '2019-01-09',
[2019-01-10] AS '2019-01-10',
[2019-01-11] AS '2019-01-11',
[2019-01-12] AS '2019-01-12'
FROM (
-- SELECT statement that produces the data
-- 1. Get all generated dates
-- 2. CROSS APPLY them with all distinct names
-- 3. JOIN them with calculted hours per day
SELECT dates.[Date], names.[Name], 10 - ISNULL(hours.[Hours], 0) AS Hours
FROM dates
CROSS APPLY (
SELECT DISTINCT Name
FROM #Table
) names
LEFT JOIN (
SELECT [Name], [Date], SUM([Hours]) AS Hours
FROM #Table
GROUP BY [Name], [Date]
) hours ON (dates.[Date] = hours.[Date]) AND (names.[Name] = hours.[Name])
) p
PIVOT (
-- Rotate data with PIVOT
SUM ([Hours])
FOR [Date] IN ([2019-01-09], [2019-01-10], [2019-01-11], [2019-01-12])
) AS pvt
Выход:
Name 2019-01-09 2019-01-10 2019-01-11 2019-01-12
David 7.0 5.0 8.0 10.0
Marcos 9.0 2.0 1.5 10.0
Sam 1.0 3.0 3.0 10.0