按子查询分组

时间:2011-05-09 09:04:22

标签: sql tsql group-by

使以下 T-SQL 查询有效的最佳方法是:

select
    count(*),
    (... a subquery that returns one result ...) as [Bar]
from Foo foo
group by [Bar]

1 个答案:

答案 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