两列中的两个不相关的查询

时间:2017-09-07 05:41:16

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

我想在一个查询结果中使用单独的列获取这两个查询的输出

我有这些查询

{{1}}

我的输出结果像这样

7 个答案:

答案 0 :(得分:5)

对每个查询使用row_number并通过此row_number连接它们。 (对我来说,你的要求不符合逻辑但是......)

SELECT e.employee
       ,b.branch
FROM
(
select Name_UM as employee 
  ,ROW_NUMBER()OVER(PARTITION BY Name_UM ORDER BY Name_UM) AS rn_emp
from Universal_Master2 
where Module_UM='empl'
)E
FULL JOIN
(
select Name_UM as branch 
  ,ROW_NUMBER()OVER(PARTITION BY Name_UM ORDER BY Name_UM) AS rn_branch
from Universal_Master2 
where Module_UM='Branch'
)B
on E.rn_emp= B.rn_branch

答案 1 :(得分:1)

试试这个:

select EMPLOYEE, BRANCH from (
select row_number() over (order by Name_UM) as Pos, Name_UM as EMPLOYEE from Universal_Master2 where Module_UM='EMPL'
) as a
full join ( 
select row_number() over (order by Name_UM) as Pos, Name_UM as BRANCH from Universal_Master2 where Module_UM='Branch'
) as b
on a.Pos = b.Pos

我认为列不相关。

答案 2 :(得分:0)

您可以按照以下方法

 WHERE Module_UM in ('Branch','empl')

select ist query
union
select second query

答案 3 :(得分:0)

试试这个:

    select EMPLOYEE.EMPLOYEE,BRANCH.BRANCH  from
    (select ROW_NUMBER() over (order by (select null))rn, Name_UM  as EMPLOYEE  from Universal_Master2 WHERE Module_UM='EMPL') EMPLOYEE
full outer join 
    (select ROW_NUMBER() over (order by (select null))rn,Name_UM  as BRANCH from Universal_Master2    WHERE Module_UM='Branch')
    BRANCH 
   on EMPLOYEE.rn =BRANCH.rn

带有一些示例数据的输出:

EMPLOYEE    BRANCH
abc         efg
ert         gtr
rt          yr

答案 4 :(得分:0)

请检查:

select 
   (CASE Module_UM WHEN 'EMPL' THEN Name_UM
   ELSE NULL END) as EMPLOYEE,  
(CASE Module_UM WHEN 'Branch' THEN Name_UM
   ELSE NULL END) as BRANCH,    
from Universal_Master2 UM 

答案 5 :(得分:0)

select X.employee,Y.branch from
(select Name_UM as employee from Universal_Master2 where Module_UM='empl') as X,
(select Name_UM as branch from Universal_Master2 where Module_UM='Branch') as Y

答案 6 :(得分:0)

要按预期获得结果,请按照以下步骤操作:

1) Add column beside both tables as rownumber
2) Insert or Update on column rownumber using function ROWNUMBER()
3) After that join both tables using that rownumber column.