垂直选择结果而不是水平结果SQL Server

时间:2011-02-27 21:26:18

标签: sql-server-2008

假设我有一张表:

a     b    c     d    e      f
---------------------------------
1.2  2.3  4.4   5.1  6.7    11.9   
7.2  2.3  4.3   5.1  4.7    3.9   
1.9  5.3  3.3   5.1  3.7    8.9   
5.2  2.7  7.4   9.1  1.7    2.9  

如果我必须计算某些东西作为列总和的乘法的sqrt

SQRT(sum(a*a)), SQRT(sum(a*b)), SQRT(sum(a*c)), SQRT(sum(a*d)), SQRT(sum(a*e)), 
SQRT(sum(a*f)), SQRT(sum(b*b)), SQRT(sum(b*c)), SQRT(sum(b*d)).... SQRT(sum(f*f))

结果:

id  result  operation
-----------------------------
1    x       a*a
2    y       a*b
...  ...     ...
n    z       f*f  

而不是:

a*a     a*b   ...     f*f 
----------------------------
 x       y    ...      z

目前查询是

SELECT SQRT(sum(a*a)) AS a*a, SQRT(sum(a*b)) AS a*b, ...  , SQRT(sum(f*f)) AS f*f 
FROM Sometable

2 个答案:

答案 0 :(得分:1)

With Inputs As
    (
    Select 1 As RowNum, 1.2 As a, 2.3 As b, 4.4 As c, 5.1 As d, 6.7 As e, 11.9 As f
    Union All Select 2, 7.2, 2.3, 4.3, 5.1, 4.7, 3.9   
    Union All Select 3, 1.9, 5.3, 3.3, 5.1, 3.7, 8.9   
    Union All Select 4, 5.2, 2.7, 7.4, 9.1, 1.7, 2.9 
    )
    , NormalizedInputs As
    (
    Select RowNum, 'a' As ColName, a As Value From Inputs
    Union All Select RowNum, 'b', b From Inputs
    Union All Select RowNum, 'c', c From Inputs
    Union All Select RowNum, 'd', d From Inputs
    Union All Select RowNum, 'e', e From Inputs
    Union All Select RowNum, 'f', f From Inputs
    )
Select N1.RowNum, Sqrt( Sum( N1.Value * N2.Value ) )
From NormalizedInputs As N1
    Left Join NormalizedInputs As N2
        On N2.RowNum = N1.RowNum
            And N2.ColName >= N1.ColName
Group By N1.RowNum

答案 1 :(得分:1)

DECLARE @T TABLE(
id INT PRIMARY KEY, 
a FLOAT,
b FLOAT,
c FLOAT,
d FLOAT,
e FLOAT, 
f FLOAT
)

INSERT INTO @T
SELECT * FROM (VALUES
(1, 1.2,2.3,4.4,5.1,6.7,11.9),
(2, 7.2,2.3,4.3,5.1,4.7,3.9), 
(3, 1.9,5.3,3.3,5.1,3.7,8.9), 
(4, 5.2,2.7,7.4,9.1,1.7,2.9) )  T(id,a,b,c,d,e, f)

;WITH U AS
(
SELECT * 
FROM @T
UNPIVOT (o FOR col IN (a,b,c,d,e, f)) unpvt
)
SELECT u1.col + '*' + u2.col as operation, SQRT(sum(u1.o*u2.o)) AS result
FROM U u1 JOIN U u2 ON u1.id=u2.id  AND u1.col <= u2.col
GROUP BY u2.col, u1.col
ORDER BY u2.col, u1.col