使以下 T-SQL
查询有效的最佳方法是:
select
count(*),
(... a subquery that returns one result ...) as [Bar]
from Foo foo
group by [Bar]
答案 0 :(得分:7)
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)
给出错误
无法使用聚合或子查询 在用于该组的表达式中 按GROUP BY子句列表。
也许其他人可以回答为什么不允许这样做。有两种有效的方式
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
和
;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