SQL Query可选的聚合和组可能吗?

时间:2012-04-20 17:04:59

标签: sql sql-server-2008

我需要运行一个巨大的查询,并选择总结一列。我想知道是否可以做以下事情:

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

现在我收到一个错误: Msg 8120,Level 16,State 1,Line 4 “Visits.Time”列在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

3 个答案:

答案 0 :(得分:2)

我认为你可以做到以下几点:

declare @sumIt bit
set @sumIt = 1

select ID, Name,
       (CASE WHEN @sumIt=1 THEN sum(Time) ELSE min(Time) END) [timeCol]
from Visits
where ID = 123
Group by ID, Name, (CASE WHEN @sumIt=1 THEN '' ELSE Time END) 

您可以按变量将聚合函数应用于组。这种做法并不常见,但它可以解决您的问题。

答案 1 :(得分:0)

我没有测试过,但这应该可以正常工作:

select ID, Name, sum([Time]) [timeCol]
from Visits
where ID = 123
AND @sumint = 1
Group by ID, Name
UNION ALL
select ID, Name, [Time] [timeCol]
from Visits
where ID = 123
AND @sumint = 0
Group by ID, Name, [Time]

答案 2 :(得分:0)

我猜你可以采用动态的sql方法。我自己并不疯狂,我只是使用IF

declare @sumIt bit, @sql VARCHAR(1000)
set @sumIt = 0

SET @sql = '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

EXEC @sql