I am looking for some advice on how best to approach this scenario. I have been asked to produce a query that returns engineer hours. There are many engineers (rows) and many time categories (columns). Hopefully, the SQL below will clarify what i am trying to achieve, however, I am not sure that CASE statements is the best solution. There are around 30 different time categories, e.g. standard time, time and a half, etc, etc. Any help would be appreciated.
DECLARE @HOURS TABLE
(
H_Code VARCHAR(10),
H_Hours REAL,
H_Name VARCHAR(10)
)
INSERT INTO @Hours
SELECT
'A1', 8, 'Bob'
UNION ALL
SELECT
'A2', 12,'Bob'
UNION ALL
SELECT
'A3', 8, 'Bob'
UNION ALL
SELECT
'A4', 8.5, 'Bob'
UNION ALL
SELECT
'A1', 12, 'Fred'
UNION ALL
SELECT
'A2', 6, 'Fred'
UNION ALL
SELECT
'A3', 10, 'Fred'
UNION ALL
SELECT
'A4', 9, 'Fred'
SELECT
H_NAME AS Name
,SUM(CASE WHEN H_CODE = 'A1' THEN H_HOURS ELSE 0 END) AS StandardTime
,SUM(CASE WHEN H_CODE = 'A2' THEN H_HOURS ELSE 0 END) AS TimeAndHalf
,SUM(CASE WHEN H_CODE = 'A3' THEN H_HOURS ELSE 0 END) AS DoubleTime
,SUM(CASE WHEN H_CODE = 'A4' THEN H_HOURS ELSE 0 END) AS SomeOtherTime
FROM
@HOURS
GROUP BY H_NAME
** Apologies but i wasn't sure how to space out the data in the result set below...
Name | StandardTime | TimeAndHalf | DoubleTime | SomeOtherTime
Bob 8 12 8 8.5
Fred 12 6 10 9