在 TSQL 中,如何添加一个计数列来计算查询中的行数?

In TSQL, How do I add a count column that counts the number of rows in my query?

这可以通过多种方式完成,我将在最后解释。目前,我得到的工作分配包括以下内容(简化):

"Create a record each week to track the current status that has the following: account numbers (unique within each report), a random number (provided), their status (Green, Orange, or Blue), and make sure the record also has a column which tells me how many records their are this week."

不需要代码来生成随机数。

列:帐户、RanNum、状态、NumberOfRowsThisWeek

我如何添加一个列来确定查询中的行数并在该列的每一行中生成该数字,静态的?

我可能会尝试调整请求并应用上升的数字。在这种情况下我该怎么做?

编辑:SQL 服务器 2014

您没有告诉我们您使用的是哪个数据库。

在 SQL Server 中,至少在较新的版本中,您可以使用窗口函数或分析函数,并且它们在大多数其他流行的 RDBMS 中也可用

你可以在 SQL 服务器中做你想做的事,只需将其添加到你的 select

,count(*) over (partition by 1) as [NrOfRows]

分析函数执行 "standard" 查询,然后对结果集执行窗口函数。 上面的计数,计算结果集中的行数,按常量 1 划分,这当然对所有行都是稳定的,所以它给出了完整的行数。

以这种方式允许常量可能不是所有数据库的标准,也许这会在某些情况下提供更好的结果,我知道它适用于 SQL 服务器:

,count(*) over (partition by (select 1 n)) as [NrOfRows]

听起来你想做一些简单的 count() / group by query

select Account, RanNum, Status, count(*) as NumberOfRowsThisWeek
from tablename
group by Account, RanNum, Status

你我需要做的事

select Account, RanNum, Status, NumberOfRowsThisWeek
from (
   select Account, Status, count(*) as NumberOfRowsThisWeek
   from tablename
   group by Account, Status
)

因为随机数会使每一行都独一无二,从而混淆了组。