【问题标题】:How to ROWCOUNT_BIG() value with union all如何使用 union all 计算 ROWCOUNT_BIG() 值
【发布时间】:2021-05-07 09:22:21
【问题描述】:

我在 SQL Server 中有以下查询。如何获取上一个选择查询的行数如下格式?

示例查询

select ID, Name FROM Branch
UNION ALL
SELECT ROWCOUNT_BIG(), ''

样本输出

【问题讨论】:

  • 通常您会将行数添加为显示应用程序的一部分,而不是查询的一部分。

标签: sql sql-server tsql count union-all


【解决方案1】:

如果您使用 CTE,您可以将行 countunion all 一起使用:

with cte as (
    select ID, [Name]
    from dbo.Branch
)
select ID, [Name]
from cte
union all
select count(*) + 1, ''
from cte;

【讨论】:

  • 我的选择查询在 cte 中非常复杂并且有很多列。还有很多数据。那么会慢一些吗?有没有其他替代解决方案。
  • @Mahedee SQL 的特点是过早优化永远不会有回报。试一试,看看它的表现如何。我认为任何其他方式都会更复杂。
  • @Mahedee 你测试过性能吗?没有理由认为这会更慢。 SQL Server 知道有多少条记录,所以它不会重复查询两次。
  • 我的查询中存在另一个问题,即具有相同名称的多个列。 CTE 不允许。所以,我无法测试我的真实查询。
  • @Mahedee 只是其中一列的别名?这应该很容易解决。
【解决方案2】:

我认为您想查看 select 语句的总数。你可以这样做。

CREATE TABLE #test (id int)
insert into #test(id)
SELECT 1 

SELECT id from #test
union all
SELECT rowcount_big()

注意:此处,ID 将根据数据类型优先级隐式转换为 BIGINT 数据类型。 Read more

【讨论】:

  • 本质上(从性能的角度来看)与我的答案相同:)
  • @DaleK,同意你的看法。这是一种繁琐的方法
【解决方案3】:

大概,您正在某种应用程序中运行它。那么为什么不使用@@ROWCOUNT呢?

select id, name
from . . .;

select @@rowcount_big;  -- big if you want a bigint

我看不到在同一个查询中包含该值的价值。但是,如果基础查询是聚合查询,则可能有一种方法可以使用 GROUPING SETS

【讨论】:

    【解决方案4】:

    这里有两种方法。最好使用 CTE 来定义行集,以便进一步的表插入不会干扰计数。由于您使用的是 ROWCOUNT_BIG(),因此这些查询使用 COUNT_BIG()(也返回 bigint)来计算插入的行数。为了确保总数始终显示为最后一行,在SELECT 列表和ORDER BY 子句中添加了“order_num”列。

    drop table if exists #tTest;
    go
    create table #tTest(
      ID        int not null,
      [Name]    varchar(10) not null);
    
    insert into #tTest values
    (115, 'Joe'),
    (116, 'Jon'),
    (117, 'Ron');
    
    /* better to use a CTE to define the row set */
    with t_cte as (
        select * 
        from #tTest)
    select 1 as order_num, ID, [Name] 
    from t_cte
    union all
    select 2 as order_num, count_big(*), '' 
    from t_cte
    order by order_num, ID;
    
    /* 2 separate queries could give inconsistent result if table is inserted into */
    select 1 as order_num, ID, [Name] 
    from #tTest
    union all
    select 2 as order_num, count_big(*), '' 
    from #tTest
    order by order_num, ID;
    

    都返回

    order_num   ID  Name
    1           115 Joe
    1           116 Jon
    1           117 Ron
    2           3   
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-30
      • 2021-11-14
      • 1970-01-01
      • 2018-01-07
      • 2012-05-08
      • 1970-01-01
      相关资源
      最近更新 更多