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
/* 測試結果
idabcdefminValue maxValue sumValue avgValue
------ ------ ------ ------ ------ ------ ------ ----------- ----------- ----------- -----------
112346717233
2344556549665620434
*/