I need to run a huge query with the option to sum up one column. I’m wondering if it would be possible to do something like the following:
declare @sumIt bit
set @sumIt = 1
select ID, Name, CASE WHEN @sumIt=1 THEN sum(Time) ELSE Time END [timeCol]
from Visits
where ID = 123
Group by ID, Name, CASE WHEN @sumIt=1 THEN '' ELSE Time END
Right now I get an error:
Msg 8120, Level 16, State 1, Line 4
Column ‘Visits.Time’ is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
I think you can do the following:
You can apply an aggregation function to the group by variables. This isn’t commonly done, but it solves your problem.