从sql中连接相同模式的两个表中查找列的sum和max

2ic8powd  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(269)

表1

Name Marks
a    65
b    40

表2

Name Marks
c    25
b    70

总和为(65+40+25+70),最大值为70

hrysbysz

hrysbysz1#

使用union all组合两个表,然后应用聚合

select sum(marks), max(marks)
    from
    (select * from table1
    union all
    select * from table2)a
where marks>40
0g0grzrc

0g0grzrc2#

--test in your sql management

--populating test table 

declare @table1 table (name varchar(30), marks int )
declare @table2 table (name varchar(30), marks int )

insert into @table1 values ('a',65)
insert into @table1 values ('b',40)

insert into @table2 values ('c',25)
insert into @table2 values ('d',70)

**--query excluding marks<=40 from sum**

select sum(marks) as 'sum' ,max(marks) as 'max' from 

(
select * from @table1 where marks>40

union

select * from @table2 where marks>40
) table_temp

**--query showing sum, only if sum > 40**

select sum(marks) as 'sum' ,max(marks) as 'max' from 
(
select * from @table1 

union

select * from @table2 

) table_temp having sum(marks) > 40

相关问题