-5

请您帮助获取下表的查询

  A  B   C   D
-----------------
  1  5   7  -5
  2  6   8  7

我需要垂直列出的所有列的最小值、最大值和平均值。输出应如下所示。X、X、X 只是样本字母,而不是实际的最小值、最大值和平均值。

CN Min  Max   AVG 
----------------------
A  X    X     X
B  X    X     X
C  X    X     X 
D  X    X     X

CN = 列名

谁能给我这个查询?

4

2 回答 2

1

可能是这样的:

;WITH CTE
(
SELECT 'A' as CN, tbl.a as nbr FROM tbl UNION ALL
SELECT 'B', tbl.b FROM tbl UNION ALL
SELECT 'C', tbl.c FROM tbl UNION ALL
SELECT 'D', tbl.d FROM tbl
)
SELECT
    CTE.CN,
    MAX(CTE.nbr) AS Max,
    MIN(CTE.nbr) AS Min,
    AVG(CTE.nbr) AS Avg
FROM
    CTE
GROUP BY
    CTE.CN

或使用UNPIVOT

SELECT
    unpvt.CN,
    MAX(unpvt.nbr) AS Max,
    MIN(unpvt.nbr) AS Min,
    AVG(unpvt.nbr) AS Avg
FROM
(
    SELECT
        tbl.a,
        tbl.b,
        tbl.c,
        tbl.d
    FROM
        tbl
) AS p
UNPIVOT
(
    nbr FOR CN IN
    (a,b,c,d)
) AS unpvt
GROUP BY
    unpvt.CN
于 2013-10-07T06:44:54.560 回答
0

请试试:

SELECT DISTINCT 
    CN, 
    MIN(Col) over (partition by CN) [Min],
    MAX(Col) over (partition by CN) [Max],
    AVG(Col) over (partition by CN) [Avg]
FROM 
   (SELECT *
   FROM YourTable) p
UNPIVOT
   (Col FOR CN IN 
      (A, B, C, D)
)AS unpvt;
于 2013-10-07T06:45:38.330 回答