请帮助您查询下表
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 =专栏名称
有人可以给我查询吗?
答案 0 :(得分: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
答案 1 :(得分: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;