易截截图软件、单文件、免安装、纯绿色、仅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得到汉字拼音首字母存储过程:
create function [dbo].[fun_getPY]
(
@str nvarchar(4000)
)
returns nvarchar(4000)
as
begin
declare @word nchar(1),@PY nvarchar(4000)
set @PY=''
while len(@str)>0
begin
   set @word=left(@str,1)
   --如果非汉字字符,返回原字符
& ......

SQLServer获取每组前10%的数据

sqlserver2005有关键字ntile(x)和over(partition by.. order by..)子句配合.
比如获取每个表的前10%个字段。
select id , name , colid , rn from (
select * , rn = ntile (10 )
    over (partition by id order by colorder )
from syscolumns )t where rn = 1 ......

SqlServer数据库的语句及一些操作整理

临近年终,在工作之余对工作和学习中遇到的问题以及常用的一些知识点做了些整理,以备后用。本文涉及的内容为数据库,算是对开发总结(1)---数据库一文的补充。
1 对于主键设置了Identity的表,在删除表中数据后再往表中插入数据,Identity列不是从1起始了,如果想删除数据后Indentity列仍从1起始,可以用下面代码来删除数据 ......

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号