欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

解析SQLServer任意列之間的聚合

 更新時(shí)間:2013年06月27日 12:41:03   作者:  
這里介紹一個(gè)通過(guò)xml合并列并轉(zhuǎn)為行集后直接用聚合函數(shù)求值的方法,測(cè)試用例和代碼如下
sql的max之類的聚合函數(shù)只能針對(duì)同一列的n行運(yùn)算,如果對(duì)n列運(yùn)算,一般都用case 語(yǔ)句來(lái)判斷,如果列少還比較容易寫,列多了就麻煩了。
--------------------------------------------------------------------------------
/*
測(cè)試名稱:利用 XML 求任意列之間的聚合
測(cè)試功能:對(duì)一張表的列數(shù)據(jù)做 min 、 max 、 sum 和 avg 運(yùn)算
運(yùn)行原理:字段合并為 xml 后做 xquery 查詢轉(zhuǎn)為行集后聚合
*/
-- 建立測(cè)試環(huán)境
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

-- 測(cè)試語(yǔ)句
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

/* 測(cè)試結(jié)果
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
*/
您可能感興趣的文章:

相關(guān)文章

最新評(píng)論