【问题标题】:Combining the results of three queries into one dataset cross Apply or join将三个查询的结果组合成一个数据集 cross Apply 或 join
【发布时间】:2014-11-12 21:54:09
【问题描述】:

如何将三个查询的结果合并到一个数据集中?交叉申请还是加入?

create table tbl_A
(
Dept varchar(5),
DocCountA int
);

create table tbl_b
(
Dept varchar(5),
DocCountB int
);

create table tbl_c
(
Dept varchar(5),
DocCountC int
);

insert into tbl_A
values ('XX',12),('YY',14),('ZZ',16)

insert into tbl_b
values ('XX',20),('YY',25),('ZZ',27)

insert into tbl_c
values ('XX',30),('YY',35)

select * from tbl_A  
select * from tbl_B  
select * from tbl_C  

**tbl_A**  
Dept    DocCountA  
XX  12  
YY  14  
ZZ  16  


**tbl_B**  
Dept    DocCountB  
XX  20   
YY  25    
ZZ  27  

**tbl_C**  
Dept    DocCountC  
XX  30    
YY  35  

结果

Dept DocCountA DocCountB DocCountC  
XX  
YY  
ZZ    

表 C 有两个结果 ZZ 将为空白

这需要使用两个查询 三个会很棒!

从 tbl_A A 中选择 *
交叉申请
(
从 tbl_b B 中选择 B.DocCountB
其中 B.Dept=A.Dept
) 草皮

【问题讨论】:

    标签: sql cross-apply


    【解决方案1】:

    每个表上的左连接将允许您获取所有 3 个部门和计数(如果它们存在)。

    select
      a.dept, DocCountA, DocCountB, DocCountC
    from
      tbl_a a
      left join tbl_b b on a.dept = b.dept
      left join tbl_c c on a.dept = c.dept
    

    Here is a working fiddle

    【讨论】:

    • 更多连接选项:如果 TableA 中可能不存在某个部门的记录,请执行 full outer join。如果保证所有三个表都有每个部门的记录,请执行inner join。如果保证在一个(或多个)表中而不是其他表中,frominner join 将首先具有记录的表,然后是 left outer join 可能没有记录的表。
    • 非常感谢!这三个查询将使用派生查询和数据透视构建。结果将与您在上面的表格中得到的结果一样...
    • @winchmore 很高兴我们能提供帮助。请务必标记答案并在可能的情况下投票。祝你好运!
    • 这使用两个查询三个会很棒! select * from tbl_A A cross apply (select B.DocCountB from tbl_b B Where B.Dept=A.Dept) sod
    • @winchmore,我不明白,你是说我的解决方案有效吗?
    猜你喜欢
    • 1970-01-01
    • 2016-09-15
    • 1970-01-01
    • 1970-01-01
    • 2016-10-05
    • 2015-04-04
    • 2021-11-10
    • 2016-04-10
    • 1970-01-01
    相关资源
    最近更新 更多