/*------------------------------效率最低 功能:计算min-max两个整数之间的随机整数 作者: 日期:20180831 区别:在查询中嵌入count(*)计算记录总条数,效率最低 */ --SET STATISTICS IO ON; SET STATISTICS TIME ON; GO DECLARE @min INT= 1; DECLARE @max INT= 100; DECLARE @icount INT= 0; DECLARE @t TABLE ( i INT IDENTITY PRIMARY KEY ,n INT ); INSERT INTO @t (n ) SELECT FLOOR(RAND(CHECKSUM(NEWID())) * ( @max - @min + 1 )) + @min--计算min-max之间的随机整数 FROM master..spt_values AS a CROSS JOIN master..spt_values AS b; SELECT n ,COUNT(n) AS 数量 ,( SELECT COUNT(*) FROM @t ) AS 总数 ,COUNT(n) * 100.0 / ( SELECT COUNT(*) FROM @t ) AS [占比例%] FROM @t GROUP BY n; /*------------------------------效率居中 功能:计算min-max两个整数之间的随机整数 作者: 日期:20180831 区别:提前计算记录总条数赋值到变量,效率居中 */ --SET STATISTICS IO ON; SET STATISTICS TIME ON; GO DECLARE @min INT= 1; DECLARE @max INT= 100; DECLARE @icount INT= 0; DECLARE @t TABLE ( i INT IDENTITY PRIMARY KEY ,n INT ); INSERT INTO @t ( n ) SELECT FLOOR(RAND(CHECKSUM(NEWID())) * ( @max - @min + 1 )) + @min--计算min-max之间的随机整数 FROM master..spt_values AS a CROSS JOIN master..spt_values AS b; SELECT @icount = COUNT(*) FROM @t; SELECT n ,COUNT(n) AS 数量 ,@icount AS 总数 ,COUNT(n) * 100.0 / @icount AS [占比例%] FROM @t GROUP BY n; /*------------------------------效率最高 功能:计算min-max两个整数之间的随机整数 作者: 日期:20180831 区别:根据@@rowcount计算记录总条数,效率最高 */ --SET STATISTICS IO ON; SET STATISTICS TIME ON; GO DECLARE @min INT= 1; DECLARE @max INT= 100; DECLARE @icount INT= 0; DECLARE @t TABLE ( i INT IDENTITY PRIMARY KEY ,n INT ); INSERT INTO @t (n ) SELECT FLOOR(RAND(CHECKSUM(NEWID())) * ( @max - @min + 1 )) + @min--计算min-max之间的随机整数 FROM master..spt_values AS a CROSS JOIN master..spt_values AS b; SET @icount = @@ROWCOUNT; --SET @[email protected]@IDENTITY SELECT n ,COUNT(n) AS 数量 ,@icount AS 总数 ,COUNT(n) * 100.0 / @icount AS [占比例%] FROM @t GROUP BY n;
原文地址:https://www.cnblogs.com/bgbird/p/9638564.html
时间: 2024-11-08 02:39:09