首页 > 解决方案 > SQL Merge 来自同一个 SQL 表的结果

问题描述

我是 sql 新手,并试图将结果合并到 sql 查询的不同行的同一列中,如下所示。我该怎么做?

(select distinct szdoc 
 from proddta.f47047 (nolock) 
 where szvr01 = 'RC12/1810/04,3345' and sznxtr >580
) union
(select distinct szdoc 
 from proddta.f47047 (nolock) 
 where szvr01 = 'RC12/1810/04,3345' and sznxtr >580 
)

我得到这个:

szdoc
_______
18004932

预期成绩:

szdoc
_______
18004932
_______
18004932

标签: sqlsql-serverdatabase

解决方案


union删除重复项。对于此查询,您需要union all

(select distinct szdoc 
 from proddta.f47047 (nolock) 
 where szvr01 = 'RC12/1810/04,3345' and sznxtr >580
) union all
(select distinct szdoc 
 from proddta.f47047 (nolock) 
 where szvr01 = 'RC12/1810/04,3345' and sznxtr >580 
)

但是,我强烈建议改用派生表:

select szdoc 
from (select distinct szdoc
      from proddta.f47047 f
      where szvr01 = 'RC12/1810/04,3345' and
            sznxtr > 580 
     ) f cross join
     (values (1), (2)) v(n)

推荐阅读