易截截图软件、单文件、免安装、纯绿色、仅160KB

SQLServer任意列之间的聚合

SQLServer任意列之间的聚合 收藏
sql的max之类的聚合函数只能针对同一列的n行运算,如果对n列运算,一般都用case 语句来判断,如果列少还比较容易写,列多了就麻烦了。这里介绍一个通过xml合并列并转为行集后直接用聚合函数求值的方法,测试用例和代码如下
--------------------------------------------------------------------------------
/*
测试名称:利用 XML 求任意列之间的聚合
测试功能:对一张表的列数据做 min 、 max 、 sum 和 avg 运算
运行原理:字段合并为 xml 后做 xquery 查询转为行集后聚合
作者: jinjazz (近身剪)
*/
-- 建立测试环境
declare @t table (
id smallint ,
a smallint , b smallint ,
c smallint , d smallint ,
e smallint , f smallint )
 
insert into @t
select 1, 1, 2, 3, 4, 6, 7 union all
select 2, 34, 45, 56, 54, 9, 6
 
-- 测试语句
select   a.*, c.*
from @t a outer apply(
select doc=(
select * from @t as doc where id= a. id  for xml path ( '' ), type   )
) b
outer apply(
select
min ( r) as minValue,
max ( r) as maxValue,
sum ( r) as sumValue,
avg ( r) as avgValue
  from (
    select cast ( cast ( d. n. query( 'text()' ) as varchar ( max )) as int ) as r
       from doc. nodes( '/a,b,c,d,e,f' ) D( n)) tt
) c
     
/* 测试结果
 
id     a      b      c      d      e      f      minValue    maxValue    sumValue    avgValue
------ ------ ------ ------ ------ ------ ------ ----------- ----------- ----------- -----------
1      1      2      3      4      6      7      1       


相关文档:

只让指定的机器连接SQLServer服务器 收藏

只让指定的机器连接SQLServer服务器 收藏
背景
只想使某个IP的计算机才能连接到SQL Server服务器,不允许其他客户端连接。
解决方法
可以直接在防火墙中做限制,只允许与指定的IP地址建立1433的通讯。当然,从更为安全的角度来考虑,应该把1433端口改成其他的端口。
其他解决方法1(限从指定IP接入的客户端)
如果使 ......

SQLServer中的Scanf和Printf 收藏

SQLServer中有两个扩展存储过程实现Scanf和Printf功能,恰当的使用它们可以在提取和拼接字符串时大幅度简化SQL代码。
1、xp_sscanf,用它可以分解格式相对固定的字符串,这对于厌倦使用一堆substring和charindex的朋友来说不错。比如前几天的一个帖子中提出的如何分解ip地址,相对简练且通用的代码应该是下面这样
------- ......

SQLServer获取Excel中所有Sheet

E盘根目录新建一个Excel文件aa.xls后测试如下代码
use tempdb
go
if (object_id ('udf_getExcelTableNames' ) is not null )
    drop function dbo .udf_getExcelTableNames
go
create function udf_getExcelTableNames (@filename varchar (1000 ))
returns @t table (id int , name varchar ( ......

SQLServer数据集合的交、并、差集运算

 SQLServer2005通过intersect,union,except和三个关键字对应交、并、差三种集合运算。
他们的对应关系可以参考下面图示
       相关测试实例如下:
use tempdb
go
if (object_id ('t1' ) is not null ) drop table t1
if (object_id ('t2' ) is not null ) drop table t2
go ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号