I appreciate this is a generic question - I'm only after a generic answer
Lets say I have
SELECT
ActivityCode
, EmployeeID
, [StartTime] = DATEADD(Day, DATEDIFF(Day, 0, StartTime), 0)
, [IsFinshed] = CASE WHEN FinishTime IS NULL THEN 0 ELSE 1 END
, [TotalTime] = SUM(TimeWorked)
FROM MyTable
GROUP BY
ActivityCode
, EmployeeID
, DATEADD(Day, DATEDIFF(Day, 0, StartTime), 0)
, CASE WHEN FinishTime IS NULL THEN 0 ELSE 1 END
I have to keep the code in the GROUP BY and the SELECT "in step" Let's assume its a lot more complex than this example.
I can simplify the code (and its future maintenance ) by moving the calculated stuff to a CTE and then GROUPing it in the main query:
; WITH MyCTE AS
(
SELECT
ActivityCode
, EmployeeID
, [StartTime] = DATEADD(Day, DATEDIFF(Day, 0, StartTime), 0)
, [IsFinshed] = CASE WHEN FinishTime IS NULL THEN 0 ELSE 1 END
, TimeWorked
FROM MyTable
)
SELECT
ActivityCode
, EmployeeID
, [StartTime]
, [IsFinshed]
, [TotalTime] = SUM(TimeWorked)
FROM MyCTE
GROUP BY
ActivityCode
, EmployeeID
, [StartTime]
, [IsFinshed]
but is that a bad idea in terms of performance or what the optimiser can achieve?