我如何在3个需要按一个关键列分组的表中进行联接和求和

时间:2019-03-28 12:06:38

标签: sql-server tsql

我正试图联接3个表(tableA,tableB,tableC)都具有3个字段(发票,productClass,value)。tableA和tableB在productClass字段中没有值,而tableC在Value字段中没有值。所有表的发票值相同,但ProductClass不同,结果应基于发票和ProductClass求和。

create table tableA (
    Invoice varchar(100),
    ProductClass varchar(100),
    Value int
)
create table tableB (
    Invoice varchar(100),
    ProductClass varchar(100),
    Value int
)
create table tableC (
    Invoice varchar(100),
    ProductClass varchar(100),
    Value int
)

insert into tableA
values
('001','',10),
('002','',20),
('003','',30),
('004','',40)


insert into tableB
values
('001','',20),
('002','',30),
('003','',40),
('004','',50)


insert into tableC
values
('001','aaa',null),
('002','aab',null),
('003','aac',null),
('004','aad',null)



select Invoice,ProductClass,sum(Value)
from(
    select * from tableA
    union
    select * from tableB
    union
    select * from tableC
)tableD
group by Invoice,ProductClass

我希望结果会返回

Invoice - 001,002,003,004
ProductClass - aaa,aab,aac,aad
Value - 30,50,70,90

1 个答案:

答案 0 :(得分:0)

如果max()的值类似于ProductClassblank,则可以将null用于select Invoice, max(ProductClass) as ProductClass, sum(Value) as Value from(select * from tableA union select * from tableB union select * from tableC )tableD group by Invoice;

std::vector::size()