gpt4 book ai didi

sql - 按子查询分组

转载 作者:行者123 更新时间:2023-12-04 22:30:21 25 4
gpt4 key购买 nike

制作以下内容的最佳方法是什么 T-SQL 查询有效:

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)

给出错误

Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause.



也许其他人可以回答为什么不允许这样做。几种有效的方式
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

关于sql - 按子查询分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5934717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com