-4

我有一张如下表

A     B     C      D   
10   14    14     13
12   11    16     15

我的查询应该检索如下答案:

E
14
16

如何编写查询来显示它?

4

3 回答 3

4

在这种情况下,蛮力是最有效的方法。打字很痛苦,但速度最快:

select (case when A >= B and A >= C and A >= D then A
             when B >= C and B >= D then B
             when C >= D then C
             else D
        end) E
from t;
于 2013-08-14T11:20:02.257 回答
1

这适用于 MS-Sqlserver 2005+:

编辑:正如@hvd 建议的那样

declare @t table(A int, B int, C int, D int)
insert @t values(10,14, 14, 13),(12,11, 16, 15)

select y.E from @t
cross apply
(
select max(E) E from
(
select a as E
union all
select b
union all
select c
union all
select d
)x 
)y

结果:

E
14
16
于 2013-08-14T11:18:03.253 回答
0
Create Table #sample (
                [col1] int ,
                [col2] int ,
                [col3] int ,
                [col4] int 
);

INSERT INTO #sample 
(A, B, C, D)
VALUES
(10, 14, 14, 13),
(12, 11, 16, 15);

--Solution
select *, Row_Number() Over (Order By getdate()) Rid into #temp From #sample

Declare @Cols as Varchar(max)
Set @Cols=''
select @Cols = @Cols + ',[' + name + ']' from tempdb..syscolumns where id=object_id('tempdb..#temp')
and name <> 'Rid'

Select @Cols = Right(@Cols,len(@Cols)-1)
exec ('Select Rid,Max(val) maxval from #temp t
                                                Unpivot(val For data in (' + @Cols + ')) as Upvt
                                Group by Rid')

Drop table #temp
Drop table #sample
于 2013-08-14T11:23:05.193 回答