Mysql 加入、分组、求和
假设我有这张桌子Mysql 加入、分组、求和,mysql,sql,group-by,inner-join,where,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 如果苹果的预期最大值为10,胡萝卜为5,香蕉为15,则输出表将为 table o
tableA
ID value
1 5
1 5
3 10
2 4
2 2
1 2
tableB
ID Name
1 apple
2 carrot
3 banana
如果苹果的预期最大值为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子句上我需要什么选项来实现这一点
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 aggregate函数代替SUM,内部子查询将它们正常分组,然后主查询将处理限制结果的操作
SELECT * FROM
(select
b.id,
b.name as name,
SUM(a.value) as the_sum
from tableA a inner join tableB b
on a.Id = b.id
group by b.name, b.id
) y
where (name = 'apple' and the_sum >= 10) OR
(name = 'banana' and the_sum >= 15) OR
(name = 'carrot' and the_sum >= 5)
您的示例数据似乎已更改,请尝试此选项。我认为ID不必跟随tableA/tableB的ID,ID是根据结果自动生成的
SELECT * FROM
(select
b.id,
b.name as name,
SUM(a.value) as the_sum
from tableA a inner join tableB b
on a.Id = b.id
group by b.name, b.id
) y
where (name = 'apple' and the_sum >= 10) OR
(name = 'banana' and the_sum >= 15) OR
(name = 'carrot' and the_sum >= 5)
如果您有另一个表来设置每个名称的阈值,那就太好了假设可以在表B中指定阈值(有意义):
演示:这在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
您的
分组依据
用法无效。您使用的是哪种DBMS?获取输出结果的逻辑是什么?对于ID=1
的示例,如何从tableA
和tableB
中获取name='banana'
和value=10
?问题已更新。它是mysqlhi Pham,我加上了1的所有值,然后我们需要检查胡萝卜是否超过了最大值。如果是,则添加查询结果。更新了表,因为GROUP BY无效,将在较新的MySQL版本上引发错误(除非处于兼容模式),并在较旧的MySQL版本上返回不可预测的结果。常规GROUP BY规则说:如果指定了GROUP BY子句,则SELECT列表中的每个列引用必须标识一个分组列或是集合函数的参数!嗨,这是mysql吗?这是我第一次看到这样的结果。如果得到预期的结果,只需要从表名中删除这些哈希值。@ukaszKamiński oh yep很抱歉,我是在我的计算机上测试的,不想手动删除表。已更新代码。很遗憾,无法在表B中指定树名。但这是有道理的。