Resolve aggregation between any columns in SQL Server

Source: Internet
Author: User
Tags min

SQL Max such aggregate functions can only be for the same column of n row operations, if the N column operations, generally use case statements to judge, if the column is relatively easy to write, the list of more trouble.
--------------------------------------------------------------------------------
/*
Test name: Using XML Find aggregations between arbitrary columns
Test functionality: Make min, Max, SUM, and AVG operations on a table's column data
How it works: After a field is merged into XML, an XQuery query is converted to a rowset
/
--Establish a measurement Test environment
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, 5 4, 9, 6

--Test statement
Select A.*, c.*
from @t a outer apply (
Select doc= (
Select * from @t as Doc where id= an. ID for XML Path ('), type '
) B
Outer apply (
Select
min (r) as Minva Lue,
Max (R) as MaxValue,
sum (r) as Sumvalue,
Avg (r) as Avgvalue
from (
Select cast ( D. Query (' text () ') as varchar (max) as int) as R
from Doc. nodes ('/a,b, C,d,e,f ') d (n)) TT
) c

/* Test results
ID a b c d E F minvalue maxValue Sumvalue Avgvalue
--------------------------------------------------------------------------------------
1 1 2 3 4 6 7 1 7 3
2 MB 9 6 6 204
*/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.