SQL Server:解决此问题。 [英] SQL Server: Solve this problem.
问题描述
大家好,
早上好大家好。
域名:SQL Server
这里有2个表格。
1表名是:t1
2表名是:t2
Hi Everybody,
Good morning You all.
Domain: SQL Server
Here,There are 2 tables.
1 table name is: t1
2 table name is: t2
t1
col_1 col_2
1 2
null 10
3 4
89 null
5 6
t2
col_1 col_2
3 2
9 null
5 4
7 6
null 87
o/p table is
col_1 col_2
2 3
10 null
4 5
89 null
6 7
我需要o / p表的查询结果..
请解决这个问题..
这是一个面试问题到目前为止我还没有找不到答案......
谢谢和问候
Karthick
I need query result for o/p table..
Pls solve this problem..
This is one interview question so far i haven''t find answer...
Thanks&Regards
Karthick
推荐答案
使用以下sql
Hi,
Use below sql
DECLARE @t1 TABLE(col1 INT, col2 INT)
DECLARE @t2 TABLE(col1 INT, col2 INT)
INSERT INTO @t1(col1,col2)
SELECT 1,2
UNION ALL SELECT null, 10
UNION ALL SELECT 3,4
UNION ALL SELECT 89,null
UNION ALL SELECT 5,6
INSERT INTO @t2(col1,col2)
SELECT 3,2
UNION ALL SELECT 9,null
UNION ALL SELECT 5,4
UNION ALL SELECT 7,6
UNION ALL SELECT null,87
-- Given Input
SELECT col1,col2 FROM @t1
SELECT col1,col2 FROM @t2
-- Required Output
SELECT CASE WHEN ISNULL( a.col2,-1) =-1 THEN a.col1
ELSE a.col2 END ,
( SELECT col1 FROM @t2 WHERE col2 = CASE WHEN ISNULL( a.col2,-1) =-1 THEN a.col1
ELSE a.col2 END )
FROM @t1 a
逻辑:
如果col2为null则选择col2然后从t1选择col1然后
从t2选择col1,其中t2.col2 = t1.selected value
Logic:
select col2 if col2 is null then select col1 from t1 then
select col1 from t2 where t2.col2 = t1.selected value
Insert into outputtable (col1,col2)
select col2,col1 from t2 where col1 is not null and col2 is not null
union
select col2,col1 from t1 where col1 is null
union
select col1,col2 from t1 where col2 is null
我能得到这份工作吗?
(p> s。多么愚蠢的面试问题!
Do I get the job?
(p>s. what a dumb interview question!
这篇关于SQL Server:解决此问题。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!