【发布时间】:2012-08-05 15:09:00
【问题描述】:
一些非常简单的东西,但我无法让它为我工作:)
select x.name, count(x.name) from <table_name> x where ...<complex and long>...
它会抛出一个错误,即 x.name 没有与 group by 一起使用。
select x.name from <table_name> x where ...<complex and long>...
工作正常并返回例如6个名字
select count(x.name) from <table_name> x where ...<complex and long>...
也可以正常工作并返回例如6号
但是当我尝试通过以下方式添加组时,组合不起作用:
select x.name, count(x.name) from <table_name> x where ...<complex and long>...
group by x.name
它有效,但所有计数都是 1 而不是 6。
问题是,我可以先将计数放入变量中,然后编写长 sql 语句来获取名称,但我不想编写长而复杂的 select 语句两次。必须有某种方法可以在一次选择中进行组合:获取所有名称,顺便告诉我他们有多少。
谢谢
附言
name bla1 bla2
a ... ...
a foo ...
b foo ...
c ... ...
d foo ...
d foo ...
b foo ...
c foo ...
x.name where bla1 = foo 的结果是:
a
b
d
d
b
c
count(x.name) where bla1 = foo 的结果是:
6
我想要的结果:
...variable definitions
select @foundName = x.name, @numOfAllFoundNames = count(x.name)
from <table_name> x where ...<complex and long>...
应该是: @foundName = a(只是其中一个名字,不管是哪一个) @numOfAllFoundNames = 6
【问题讨论】:
-
请分享一些示例表格内容来解释它的工作方式。 COUNT 是一个聚合函数,它期望分组或应用于完整表。您真正期望的输出是什么?
标签: sql-server select count combinations