如何组合两个表的列

时间:2016-10-31 12:23:52

标签: sql-server

我有三个临时列,

  1. @Pid (PartyId bigint)包含所有Partyid

  2. 它包含的
  3. @t PartyID bigint,PartyName varchar(50)SaleQty decimal(18,2)) 财政年度15-16各方的销售历史。

  4. 它包含的
  5. @ty PartyID bigint,PartyName varchar(50)SaleQty decimal(18,2)) 16-17财政年度各方的销售历史。
  6. 我想结合两个临时表@t@ty这样的记录方式     两个财务记录的任何一方都应该在一行中。如果有的话     partyid没有表@t@ty中任何一个的条目     saleQty应该是该财政年度的零。

    我已经完成了以下查询来解决这个问题。

    select  A.PartyName,isnull(SUM(A.SaleQty),0) as TotalSale,isnull(SUM(B.SaleQty),0) as TotalSaleB  
    from @t  A 
    left join @ty B ON B.PartyId=A.PartyID
    inner join @Pid P on P.PartyID=A.PartyID and B.PartyID=P.PartyID 
    where PartyName like'%Jain'
    group by A.PartyID,A.PartyName
    

    我的输出是

     PartyName               TotalSale(15-16)      TotalSale(16-17)   
     JAIN TRADERS (DHAMPUR) 16682.00                 9699.00
    

    我想要的结果应该是

     PartyName               TotalSale(15-16)      TotalSale(16-17)   
     JAIN TRADERS (DHAMPUR)   389.00                    139.00
     Sourav Traders           3899.00                   0.00
     Tickrej Traders         0.00                      0.00
    

    但我无法得到理想的结果。请帮帮我一个。

2 个答案:

答案 0 :(得分:1)

试试这个:

declare  @Pid table (PartyId bigint)
insert into @Pid values (1)
insert into @Pid values (2)
insert into @Pid values (3)
insert into @Pid values (4)


declare @t table (PartyID bigint, PartyName varchar(50), SaleQty decimal(18,2))
insert into @t values(1, 'a', 10)
insert into @t values(1, 'c', 5)
insert into @t values(2, 'b', 10)
insert into @t values(4, 'b', 20)

declare @ty table(PartyID bigint,PartyName varchar(50), SaleQty decimal(18,2))
insert into @ty values(1, 'a', 10)
insert into @ty values(2, 'c', 15)
insert into @ty values(2, 'b', 10)


select c.PartyID as PartyID, ISNULL(sum(A.SaleQty), 0) as TotalSale15_16 into #A
from @t  A right join @Pid c on A.PartyID = c.PartyId
group by C.PartyID

select c.PartyID as PartyID,ISNULL(sum(B.SaleQty), 0) as TotalSale16_17 into #B
from @ty  B right join @Pid c on  B.PartyID = c.PartyId
group by C.PartyID

select A.PartyID, ISNULL(a.TotalSale15_16, 0) as TotalSale16_17, ISNULL(b.TotalSale16_17, 0) as TotalSale16_17 
from #A a join #B b on a.PartyID = b.PartyID

drop table #A
drop table #B


result:

PartyID TotalSale16_17  TotalSale16_17
1   15.00   10.00
2   10.00   25.00
3   0.00    0.00
4   20.00   0.00

答案 1 :(得分:1)

您需要@Pid作为“基础”表,并将两个表连接到它。 您还需要使用COALESCE(或ISNULL)从其所在的临时表中获取聚会名称。

SELECT COALESCE(A.PartyName, B.PartyName), 
       COALESCE(SUM(A.SaleQty, 0)) TotalSale_t,
       COALESCE(SUM(B.SaleQty, 0)) as TotalSale_ty
FROM @Pid C
LEFT JOIN @t A ON C.PartyId = A.PartyId
LEFT JOIN @ty B ON C.PartyId = B.PartyId
GROUP BY A.PartyName, B.PartyName