假设我有下表
Fruit | Price | Fruit | Price | State
-----------------------------------------------------
apple | 4 | banana | 3 | NY
apple | 6 | banana | 5 | CA
apple | 1 | banana | 2 | PA
orange | 4 | pear | 5 | FL
orange | 3 | pear | 4 | OH
我想问以下问题:
在所有州,fruit1 的价格都比 fruit2 贵吗?
所以对所有配对都问这个问题。
在所有州,苹果的价格都比香蕉贵吗?
在所有州,橙色的价格都比梨贵吗?
继续询问任何其他现有对
所以我假设我需要编写的查询需要以某种方式首先对出现在多行中的对进行分组。我该怎么做?
最佳答案
所以你会这样做:
select fruit1, fruit2
from t
group by fruit1, fruit2
having sum(price1 > price2) = count(*);
即进行聚合。计算水果 1 的价格大于水果 2 的价格的次数。如果这始终为真,则计数等于总计数。
如果数据全部在一张表中:
select t1.fruit, t2.fruit
from t t1 join
t t2
on t1.state = t2.state and t1.fruit <> t2.fruit
group by t1.fruit, t2.fruit
having sum(t1.price > t2.price) = count(*);
关于mysql - 如何对重复的对进行分组并对它们编写查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53037990/