有一个表roasts
,其中包含三列country
、country2
、country3
。这些列用于指示混合咖啡来自哪些国家/地区。因此,国家名称可以出现在三列中的任何一列中。虽然我可以对任何给定的列进行计数,但我想计算一个值在所有三个国家/地区列中出现的次数。
我想在 Rails/ActiveRecord 中执行此操作。我已经得到了下面的 SQL,但是这个输出是不正确的:
SELECT country, country2, country3, COUNT(*) AS CountryCount FROM roasts GROUP BY country, country2, country3;
我怀疑这就是我分组的方式。
最佳答案
您应该有一个名为 CoffeeCountries
的表,每个国家/地区的每种混合都有一行。我强烈建议您更改数据结构。
对于您的数据结构,您需要对数据进行逆透视。因为你的数据很小而且你可能不熟悉横向连接,我将使用union all
方法:
select country, count(*)
from ((select country1 as country from roasts) union all
(select country2 as country from roasts) union all
(select country3 as country from roasts)
) c
where country is not null
group by country
order by count(*) desc;
如果您有一张大表,我会推荐横向连接。此版本扫描表格三次(每个国家一次)。
关于sql - 在三个单独的列中计算值 - Rails/SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48563415/