我可以从同一个表中的多个列中获取MAX()
和MIN()
:
Select
max(Maximo) as Maximo,
min(Minimo) as Minimo
From(
SELECT
MAX(COLUMN1) AS Maximo,
MIN(COLUMN2) AS Minimo
FROM TABLE1
WHERE
COND1= 'A' and
COND2= 'X'
UNION
SELECT
MAX(COLUMN3) AS Maximo,
MIN(COLUMN4) AS Minimo
FROM TABLE1
WHERE
COND1= 'A' and
COND2= 'X'
UNION
SELECT
MAX(COLUMN5) AS Maximo,
MIN(COLUMN6) AS Minimo
FROM TABLE1
WHERE
COND1= 'A' and
COND2= 'X'
UNION
SELECT
MAX(COLUMN7) AS Maximo,
MIN(COLUMN8) AS Minimo
FROM TABLE1
WHERE
COND1= 'A' and
COND2= 'X'
) x
但这看起来很难看。所以我正在尝试使用UNPIVOT
:
SELECT
MIN (v) AS MinValue,
MAX (v) AS MaxValue
FROM
TABLE1 UNPIVOT (
v FOR nValue IN (
COLUMN1,
COLUMN2,
COLUMN3,
COLUMN4,
COLUMN5,
COLUMN6,
COLUMN7,
COLUMN8
)
) AS U
我收到以下错误:
[Err] 42000 - [SQL Server]Incorrect syntax near the keyword 'FOR'.
应该是什么?感谢。
答案 0 :(得分:0)
似乎您可以使用CROSS APPLY
轻松地使用VALUES
来撰写此内容,以获得最终结果:
SELECT Maximo = max(maxVal),
Minimo = min(minVal)
FROM table1 t
CROSS APPLY
(
VALUES
(COLUMN1, COLUMN2),
(COLUMN3, COLUMN4),
(COLUMN5, COLUMN6),
(COLUMN7, COLUMN8)
) c (maxVal, minVal)
WHERE t.COND1= 'A'
AND t.COND2= 'X';
见SQL Fiddle with Demo。这会删除列对,然后您只需抓住每列的max
/ min
即可。