我有一组值为
的行
我希望以下OutPut具有单独的Max和min值
抱歉这个可怜的prntsceen。我不知道如何在stackoverflow中绘制表格。
答案 0 :(得分:10)
select value1, value2, value3, value4,
[min]=(select min(value) from (
select value1 union all
select value2 union all
select value3 union all
select value4) X(value)),
[max]=(select max(value) from (
select value1 union all
select value2 union all
select value3 union all
select value4) Y(value))
from tbl;
要将NULL识别为 min 值,请使用以下代码
select value1, value2, value3, value4,
[min]=(select TOP(1) value from (
select value1 union all
select value2 union all
select value3 union all
select value4) X(value)
ORDER BY value ASC),
[max]=(select TOP(1) value from (
select value1 union all
select value2 union all
select value3 union all
select value4) X(value)
ORDER BY value DESC)
from tbl;
答案 1 :(得分:2)
答案 2 :(得分:2)
试试这个 -
DECLARE @temp TABLE
(
Value1 INT
, Value2 INT
, Value3 INT
, Value4 INT
)
INSERT INTO @temp (Value1, Value2, Value3, Value4)
VALUES
(NULL, 1, 1, NULL),
(NULL, 1, 2, NULL),
(NULL, 2, 2, NULL),
(NULL, 2, 2, NULL),
(1, 1, 1, 1),
(2, 2, 1, 2),
(1, 1, 1, NULL),
(2, 2, 3, 2),
(2, 2, 2, 2),
(1, 1, 1, 1)
SELECT
Value1
, Value2
, Value3
, Value4
, MinValue = (
SELECT TOP 1 value
FROM (
SELECT value = value1
UNION
SELECT value2
UNION
SELECT value3
UNION
SELECT value4
) mn
ORDER BY value
)
, MaxValue = (
SELECT MAX(value)
FROM (
SELECT value = value1
UNION
SELECT value2
UNION
SELECT value3
UNION
SELECT value4
) mx
)
FROM @temp
结果窗口:
答案 3 :(得分:1)
请尝试:
declare @T table
(
id int,
num1 int,
num2 int,
num3 int,
num4 int,
num5 int
)
insert into @T values
(1, 6, 51, NULL, 99, 34),
(2, 222, 251, 24, 299, 234),
(3, NULL, NULL, NULL, NULL, NULL)
select * From @T
SELECT id,
(SELECT
(CASE WHEN (num1+num2+num3+num4+num5) IS NULL THEN NULL
ELSE MIN(v) end)
FROM (VALUES (num1),
(num2),
(num3),
(num4),
(num5)) AS value(v)) as [MinVal],
(SELECT MAX(v)
FROM (VALUES (num1),
(num2),
(num3),
(num4),
(num5)) AS value(v)) as [MaxVal]
FROM @T