我对 SQL 很陌生。我认为这相当简单,但我无法在网上找到直接的答案。
我正在编写一个简单的 SQL 查询,以按枚举列对数据库记录进行分组,并显示每个值的计数。它工作正常,但输出显示枚举整数,我希望它显示该枚举值的字符串键。
以下是 SQL 查询的示例:
SELECT COUNT(a.sound) as "Sound Count", a.sound
FROM animals a
GROUP BY a.sound
这是枚举定义:
enum sound: {
bark: 0,
meow: 1,
moo: 2
}
这是查询的输出:
Sound Count Sound
2 0
4 1
3 2
而我真的想要:
Sound Count Sound
2 bark
4 meow
3 moo
最佳答案
您正在使用 SQL 向数据库询问信息,因此它不会了解您的 Rails 枚举。您需要使用 Rails 进行查询:
Animals.all.group(:sound).count(:sound)
=> {"bark"=>2, "meow"=>4, "moo"=>3}
对于 Postgresql 的纯 sql 答案:
SELECT temp.sound_count,
CASE
when temp.sound = 0 then 'bark'
when temp.sound = 1 then 'meow'
when temp.sound = 2 then 'moo'
END
AS my_sound
FROM (SELECT COUNT(s.sound) as sound_count, a.sound from animals a
GOUP BY a.sound)
AS temp;
关于sql - 如何在 SQL 查询中显示枚举字符串键而不是整数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61349643/