解析SQLServer任意列之間的聚合
更新時間:2013年06月27日 12:41:03 作者:
這里介紹一個通過xml合并列并轉(zhuǎn)為行集后直接用聚合函數(shù)求值的方法,測試用例和代碼如下
sql的max之類的聚合函數(shù)只能針對同一列的n行運算,如果對n列運算,一般都用case 語句來判斷,如果列少還比較容易寫,列多了就麻煩了。
--------------------------------------------------------------------------------
/*
測試名稱:利用 XML 求任意列之間的聚合
測試功能:對一張表的列數(shù)據(jù)做 min 、 max 、 sum 和 avg 運算
運行原理:字段合并為 xml 后做 xquery 查詢轉(zhuǎn)為行集后聚合
*/
-- 建立測試環(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
-- 測試語句
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
/* 測試結(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
*/
--------------------------------------------------------------------------------
/*
測試名稱:利用 XML 求任意列之間的聚合
測試功能:對一張表的列數(shù)據(jù)做 min 、 max 、 sum 和 avg 運算
運行原理:字段合并為 xml 后做 xquery 查詢轉(zhuǎn)為行集后聚合
*/
-- 建立測試環(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
-- 測試語句
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
/* 測試結(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)文章
配置SQL Server數(shù)據(jù)庫恢復(fù)模式(2種方法)
這篇文章主要介紹了配置SQL Server數(shù)據(jù)庫恢復(fù)模式的兩種方法,需要了解的朋友可以參考下2015-10-10