int我正在寻找一个 SQL Server 查询,它返回仅包含(或)的表的最大值floats:
create table tab
(
temp1 int,
temp2 int,
temp3 int,
temp4 int
)
insert into tab
values (1, 2, 3, 4),
(5, 6, 7, 8),
(9, 10, 11, 12)
我想得到12回报。
有可能以简单的方式吗?
int我正在寻找一个 SQL Server 查询,它返回仅包含(或)的表的最大值floats:
create table tab
(
temp1 int,
temp2 int,
temp3 int,
temp4 int
)
insert into tab
values (1, 2, 3, 4),
(5, 6, 7, 8),
(9, 10, 11, 12)
我想得到12回报。
有可能以简单的方式吗?
在 SQL Server 中,最简单的方法可能是通过横向连接来取消透视,然后top():
select top (1) val
from tab
cross apply (values (temp1), (temp2), (temp3), (temp4)) x(val)
order by val desc
或者使用聚合而不是排序:
select max(val) val
from tab
cross apply (values (temp1), (temp2), (temp3), (temp4)) x(val)
您必须使用此代码段
SELECT MAX(TEMP) AS MAXTEMP
FROM DBO.TAB
UNPIVOT ( TEMP FOR TEMPVal IN ( TEMP1, TEMP2, TEMP3 , TEMP4) ) AS u
--fixed number of cols: temp1-4
select max(unp.theint)
from tab as t
unpivot
(
theint FOR thecol IN ( temp1, temp2, temp3, temp4)
) as unp;
--any number of cols
alter table tab add col1 int default(10) with values;
alter table tab add colx int default(100) with values;
select max(theint)
from
(
select (select t.* for xml path(''), type).query('max(/*)').value('.', 'int') as theint
from tab as t
) as src;
以简单的方式没有。通过使用动态 SQL 是的。这样的表设计违反了规范化规则,这就是编写简单高效查询能力差的原因