【问题标题】:get a new table from two tables based on the columns' values in a table in SQL server:根据 SQL Server 中表中的列值从两个表中获取一个新表:
【发布时间】:2016-02-23 22:34:36
【问题描述】:

我需要从 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

但是,这不是我想要的。我不想使用循环来做到这一点。

谢谢!

【问题讨论】:

  • 您需要加入表格,而不仅仅是列出它们。

标签: sql sql-server sql-server-2008


【解决方案1】:

我想你想要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;

【讨论】:

    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-20
      • 2020-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-23
      相关资源
      最近更新 更多