解析SQLServer任意列之间的聚合

2022-05-24 0 1,114

sql的max之类的聚合函数只能针对同一列的n行运算,如果对n列运算,一般都用case 语句来判断,如果列少还比较容易写,列多了就麻烦了。

——————————————————————————–

/*

测试名称:利用 XML 求任意列之间的聚合

测试功能:对一张表的列数据做 min 、 max 、 sum 和 avg 运算

运行原理:字段合并为 xml 后做 xquery 查询转为行集后聚合

*/


— 建立测试环境
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           7           23          3

2      34     45     56     54     9      6      6           56           204         34

*/

免责声明:
1、本网站所有发布的源码、软件和资料均为收集各大资源网站整理而来;仅限用于学习和研究目的,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 不得使用于非法商业用途,不得违反国家法律。否则后果自负!

2、本站信息来自网络,版权争议与本站无关。一切关于该资源商业行为与www.niceym.com无关。
如果您喜欢该程序,请支持正版源码、软件,购买注册,得到更好的正版服务。
如有侵犯你版权的,请邮件与我们联系处理(邮箱:skknet@qq.com),本站将立即改正。

NICE源码网 MsSql 解析SQLServer任意列之间的聚合 https://www.niceym.com/61571.html