2017-04-16 19 views
2

如何做到这一点:TSQL从3列中选择最大,然后内部联接的列

AI有3列与整数值:A,B,C表 BI有3列一个整数:x,y,z

我想选择(a,b,c)的最大值,并且内部连接x,y,z中的对应值。

实施例:

a = 1, b = 2, c = 3 

x = 7, y = 8, z = 9 

结果: 表有两列

firstColumn | secondColumn 

c   | 9 

解释:c是A,B,C的最大值和我们取的名字,而不是值 9是从第二个表中我们需要的值

在此先感谢 ps我正在使用sql server 2014

编辑:我试图做出了榜样与Excel表格

enter image description here

+0

你可以添加一些样本数据到你的问题和预期的输出? –

+0

@ M.Ali查看http://2.1m.yt/fefqfm.png我试图用excel表格做一个例子 – marto

+0

您根据_position_匹配第二列吗?对于每个可能的位置,SQL都不会在CASE语句之外执行此操作。 –

回答

1

除非两个表中只有1行,你会propably不想做一个CROSS JOIN,将参加所有记录table1全部来自table2。
所以我的猜测是,你正在寻找的东西是这样的:

select 
case 
when c > isnull(a,0) and c > isnull(b,0) then 'c' 
when b > isnull(a,0) then 'b' 
when a is not null then 'a' 
end as firstColumn, 
case 
when c > isnull(a,0) and c > isnull(b,0) then z 
when b > isnull(a,0) then y 
when a is not null then x 
end as secondColumn 
from table1 t1 
join table2 t2 on t1.table2_id = t2.id 

只是有点测试数据:

declare @table1 table (id int identity(1,1), a int, b int, c int, table2_id int default 1); 
declare @table2 table (id int, x int, y int, z int); 
insert into @table1 (a, b, c) values 
(1,2,3),(1,3,2),(2,1,3),(2,3,1),(3,1,2),(3,2,1), 
(4,5,5),(5,4,5),(5,5,4),(4,5,4),(4,4,5),(4,4,4), 
(6,7,null),(6,null,7),(null,6,7), 
(8,null,null),(null,8,null),(null,null,8),(null,null,null); 
insert into @table2 (id, x, y, z) values (1,100,200,300); 
+0

!欢呼Luk – marto

0

你对我们不支持您的需求的表结构。您需要将一个表中的行连接到另一个表中的内容。

如果存在的话,那么你可以使用(demo

SELECT t1label, 
     t2col 
FROM TableA TA 
     JOIN TableB TB 
     ON TA.rownum = TB.rownum 
     CROSS APPLY (SELECT TOP 1 * 
        FROM (VALUES('A', TA.a, TB.x), 
            ('B', TA.b, TB.y), 
            ('C', TA.c, TB.z)) v(t1label, t1col, t2col) 
        ORDER BY t1col DESC) CA 

在事件表A行有它undeterministic将被选择的相同的最大值两个或多个列。

相关问题