Group by a subquery
What is the best way of making the following T-SQL
q开发者_开发问答uery valid:
select
count(*),
(... a subquery that returns one result ...) as [Bar]
from Foo foo
group by [Bar]
SELECT COUNT(*),
(SELECT TOP 1 name
FROM sys.objects
ORDER BY object_id%number) name
FROM master..spt_values
WHERE number > 0
GROUP BY (SELECT TOP 1 name
FROM sys.objects
ORDER BY object_id%number)
Gives the error
Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause.
Maybe someone else can answer why this is not allowed. A couple of ways which are valid
SELECT COUNT(*),
oa.name
FROM master..spt_values
OUTER APPLY (SELECT TOP 1 name
from sys.objects
ORDER BY object_id%number) oa
WHERE number > 0
GROUP BY oa.name
and
;WITH T AS
(
SELECT number,
(SELECT TOP 1 name
from sys.objects
ORDER BY object_id%number) name
FROM master..spt_values
WHERE number > 0
)
SELECT COUNT(*),
name
FROM T
GROUP BY name
精彩评论