DECLARE @someTable TABLE (empid INT, Meal VARCHAR(10), [Day] INT, Value INT);
INSERT INTO @someTable(empid, Meal, [Day], Value)
SELECT 1, 'Brkfst', 1, 10 UNION ALL
SELECT 1, 'Brkfst', 1, 20 UNION ALL
SELECT 1, 'Brkfst', 2, 30 UNION ALL
SELECT 1, 'Lunch', 3, 40 UNION ALL
SELECT 2, 'Brkfst', 1, 50 UNION ALL
SELECT 2, 'Lunch', 2, 60 UNION ALL
SELECT 2, 'Brkfst', 1, 70 UNION ALL
SELECT 2, 'Brkfst', 2, 80;
WITH SRC AS (
SELECT empid, Meal, [Day], Value
FROM @someTable
)
SELECT empid, Meal, [1] AS Day1, [2] AS Day2, [3] AS Day3
FROM SRC
PIVOT(Sum(Value) FOR [Day] IN([1], [2], [3])) P
Результаты:
empid Meal Day1 Day2 Day3
----------- ---------- ----------- ----------- -----------
1 Brkfst 30 30 NULL
2 Brkfst 120 80 NULL
1 Lunch NULL NULL 40
2 Lunch NULL 60 NULL