假设我有这张桌子
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 * 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 是根据结果自动生成的。
如果您有另一个表可以设置每个名称的阈值,那就太好了
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句