我需要从SQL server中的两个表中获取一个新表:
tbl1:
id value
1 abc
2 abd
3 dft
TBL2:
num abc abd dft
1 5 9 0
2 8 0 7
如果tbl2中的列不为0,则从tbl1获取id,如:
num id
1 1 (abc <> 0 in tbl2)
1 2 (abd <> 0 in tbl2)
2 1 (abc <> 0 in tbl2)
2 3 (dft <> 0 in tbl2)
我的SQL查询:
select tbl2.num, case when (tbl2.abc != 0 ) then select tbl1.id from tbl1 end as id
from tbl2, tbl1
但是,这不是我想要的。我不想用循环来做它。
谢谢!
答案 0 :(得分:2)
我想你想要union all
:
select num, 1 as id from tbl2 where abc <> 0
union all
select num, 2 as id from tbl2 where abd <> 0
union all
select num, 3 as id from tbl2 where dft <> 0;
如果你想从第一张表中获取ID:
select t2.num, t1.id
from tbl2 cross join
(select id from tbl1 where value = 'abc') t1
where abc <> 0
union all
select num, t1.id
from tbl2 cross join
(select id from tbl1 where value = 'abd') t1
where abd <> 0
union all
select num, t1.id
from tbl2 cross join
(select id from tbl1 where value = 'dft') t1
where dft <> 0;
答案 1 :(得分:2)
你可以像这样使用unpivot:
;WITH tbl1 AS (
SELECT * FROM (VALUES
(1, 'abc'),
(2, 'abd'),
(3, 'dft')) as t1(id, value)
)
,tbl2 AS (
SELECT * FROM (VALUES
(1, 5, 9, 0),
(2, 8, 0, 7)) as t2(num, abc, abd, dft)
)
--Unpivot the table.
SELECT num, tbl1.id
FROM
(SELECT num,
CASE WHEN abc != 0 THEN 1 ELSE NULL END as abc,
CASE WHEN abd != 0 THEN 1 ELSE NULL END as abd,
CASE WHEN dft != 0 THEN 1 ELSE NULL END as dft
FROM tbl2) p
UNPIVOT
(value FOR id IN
(abc, abd, dft)
)AS unpvt
LEFT JOIN tbl1 on tbl1.value = unpvt.id
结果:
num id
----------- -----------
1 1
1 2
2 1
2 3