除非两个表中只有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);
你可以添加一些样本数据到你的问题和预期的输出? –
@ M.Ali查看http://2.1m.yt/fefqfm.png我试图用excel表格做一个例子 – marto
您根据_position_匹配第二列吗?对于每个可能的位置,SQL都不会在CASE语句之外执行此操作。 –