JOIN,GROUP BY,SUM问题Mysql

时间:2017-03-16 08:31:52

标签: mysql sql group-by inner-join where

假设我有这张表

tableA
ID       value 
1          5
1          5
3          10
2          4 
2          2
1          2

tableB
ID        Name       
1         apple      
2         carrot      
3         banana     

如果apple的预期最大值是10,胡萝卜是5,香蕉是15,输出表将是

table output
ID     Name       value
1      apple      12
2      carrot     6

我需要解决这个问题的SQL语句?

到目前为止我做了什么:

SELECT a,ID, b.name , sum(a.valueSUM) AS value FROM tableA a
INNER JOIN tableB b 
ON a.id = b.id 
GROUP BY id 

我需要在WHERE子句中选择哪些选项来解决这个问题?

4 个答案:

答案 0 :(得分:2)

内部子查询通常对它们进行分组,然后主查询处理限制结果的内容。

AfterTargets="CustomBuildStep"

您的示例数据似乎已更改,请尝试此操作。我认为ID不必遵循tableA / tableB的id,并且根据结果自动生成id。

如果您有另一个表来设置每个名称的阈值

,那就太好了

答案 1 :(得分:2)

假设可以在tableB中指定阈值(有意义):

SELECT a.ID, b.name, sum(a.value) AS value
FROM tableA a
INNER JOIN tableB b 
ON a.id = b.id 
GROUP BY a.ID, b.name, b.Threshold
HAVING sum(a.value) > b.Threshold;

演示:http://rextester.com/ICOQF10295

答案 2 :(得分:0)

SELECT TableB.id, TableB.Name, MAX(TableA.value) AS Value
FROM TableA INNER JOIN TableB ON
TableA.id = TableB.id
GROUP BY TableB.id, TableB.Name

使用MAX聚合函数

而不是SUM

答案 3 :(得分:0)

这适用于SQL Server

--Existing tables
create table #tableA (ID int, value int)
create table #tableB (ID int, Name varchar(30))


insert into #tableA
select 1 , 5 union all  
select 1 , 5 union all  
select 3 , 10 union all  
select 2 , 4 union all  
select 2 , 2 union all  
select 1 , 2

insert into #tableB    
select 1 , 'apple' union all  
select 2 , 'carrot' union all 
select 3 , 'banana'   

--Create new temporary table @tableC

create table #tableC (ID int, MAXvalue int)


insert into #tableC    
select 1 , 10 union all  
select 2 , 5  union all  
select 3 , 15 


select c.ID,b.Name, a.value from #tableC c
inner join #tableB b on b.ID = c.ID
inner join (
    select ID,SUM(value) as value from #tableA
    group by ID
) a on a.ID = c.ID
where a.value >= c.MAXvalue

drop table #tableA
drop table #tableB
drop table #tableC