Resolve aggregation _mssql between any columns in SQL Server

Source: Internet
Author: User
SQL Max and 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: Use XML to find aggregations between arbitrary columns
Test function: do min, Max, SUM, and AVG operations on a table's column data
How it works: When a field is merged into XML, an XQuery query is converted to a rowset after aggregation
*/
--Establish a 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, 54, 9, 6

--Test statement
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

/* Test Results
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
*/
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.