【问题标题】:sql server select into variable and count resultsql server 选择变量并计算结果
【发布时间】: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


【解决方案1】:

试试这个:

select x.name, count(x.name) over () cnt 
from <table_name> x where ...<complex and long>...

【讨论】:

  • 很酷,这也可以,但实际上它是如何工作的。这个在 () cnt 上的构造是什么???
  • 我认为这就像一个带有 group by 的附加选择,但更高效、更舒适。有关更多信息,请参阅msdn.microsoft.com/en-us/library/ms189461.aspx
【解决方案2】:

最简单的方法是在查询后使用@@rowcount

select x.name from <table_name> x where ...<complex and long>...

select 'the number of rows is:', @@rowcount

顺便说一句,如果您请求一个非聚合字段 (name) 和一个聚合字段 (count(name)),您必须提供一个 group by 来告诉服务器要计算什么 ;您会看到 1,因为 group by namecount 应用于集合中的每个 不同 名称 - 例如如果名称重复,您会看到少 1 行和 2

【讨论】:

    【解决方案3】:

    您可以在选择名称后使用@@ROWCOUNT 来获取复杂查询返回的行数。否则,没有简单的方法可以在选择每个名称的同一查询中获取名称的数量。

    【讨论】:

      【解决方案4】:

      你几乎猜对了。

      ...variable definitions
      set @numOfAllFoundNames = 0;
      select @foundName = x.name, @numOfAllFoundNames = @numOfAllFoundNames+1
      from <table_name> x where ...<complex and long>...
      

      【讨论】:

      • -1 因为 "@foundName = x.name" 仅适用于单行选择,而 "@numOfAllFoundNames = @numOfAllFoundNames+1" 仅对多行选择有意义。
      • @forcey:很酷,这也有效,谢谢(@JohnC 我不明白你的意思,但我已经验证了它并且它对我有用,当名字是 0,1 ,>1,所以它按预期工作)
      • @JohnC 你确定@foundName=x.name 只适用于单行选择吗?
      • @forcey,一个变量一次只能有一个值。
      • @JohnC 并且操作只希望返回一个(任何一个)值。最后一个值完全符合条件。
      【解决方案5】:

      这是很少使用的 COMPUTE 子句的工作:

      SELECT x.name
      FROM [table]
      WHERE [... ]
      COMPUTE COUNT(x.name)
      

      请注意 COMPUTE 已被弃用。

      【讨论】:

      • 因为还有其他有效的答案,我不会使用贬低的计算:),谢谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-02
      • 2023-03-22
      • 1970-01-01
      • 2023-04-08
      相关资源
      最近更新 更多