sql-将匹配结果列在彼此旁边

r6l8ljro  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(286)

我试图得到匹配的结果,以便根据主键列彼此相邻地列出,不匹配的结果可以是空白或不适用。
我正在使用的查询不起作用,因为来自初始表的结果只是重复它们自己。应用“distinct”对我来说对任何列都不起作用。
示例查询:

IF EXISTS   (
            SELECT *
            FROM tempdb.dbo.sysobjects
            WHERE id = Object_id(N'tempdb..#TABLE_A')
            )
        BEGIN
            DROP TABLE #TABLE_A
        END

IF EXISTS   (
            SELECT *
            FROM tempdb.dbo.sysobjects
            WHERE id = Object_id(N'tempdb..#TABLE_B')
            )
        BEGIN
            DROP TABLE #TABLE_B
        END

select Animal_1, Qty_1
    into #TABLE_A
from TABLE_AA

select Animal_2, SUM(Qty_2) 
    into #TABLE_B
from TABLE_BB 
group by Animal_2

select  
        Animal_1, 
        Qty_1,
        Animal_2, 
        Qty_2 
from #TABLE_A, #TABLE_B

结果

bvhaajcl

bvhaajcl1#

干得好

select  
        Animal_1,  Qty_1, Animal_2, Qty_2 
from #TABLE_A left join #TABLE_B
ON Animal_1=Animal_2
Union
select  
        Animal_1,  Qty_1, Animal_2, Qty_2 
from #TABLE_A Right join #TABLE_B
ON Animal_1=Animal_2

相关问题