Select SQL table 列表中的第一个匹配字符串值
Select first matching string value in list from SQL table
我想查询 Table 和 return 给定行的 table 中最精细的频率。样本 table 和期望的结果如下。我已经尝试了查询的几次迭代,但还没有破解它。
"most granular frequency" 我的意思是我想 return 这个集合中任何行的第一个匹配 ['hourly', 'daily', 'weekly', 'monthly'] 作为名为 min_frequency
的新列
Table
----------------------------------
id | name | frequency
----------------------------------
----------------------------------
1 | apples | hourly
----------------------------------
2 | apples | daily
----------------------------------
3 | oranges | weekly
----------------------------------
4 | oranges | monthly
----------------------------------
想要的结果:
name | min_frequency
----------------------------------
----------------------------------
apples | hourly
----------------------------------
oranges | weekly
----------------------------------
当前尝试:
SELECT name, (
CASE
WHEN frequency='hourly' then frequency
WHEN frequency='daily' then frequency
WHEN frequency='weekly' then frequency
WHEN frequency='yearly' then frequency
END
) as min_frequency from Table
GROUP BY name, min_frequency
您可以将 distinct on
与条件排序逻辑一起使用:
select distinct on (name) *
from mytable
order by
name,
case frequency
when 'hourly' then 1
when 'daily' then 2
when 'weekly' then 3
when 'monthly' then 4
end
尽管您可以使用巨大的 case
表达式,但数组对此很方便:
select distinct on (name) t.*
from t
order by name,
array_position(array['hourly', 'daily', 'weekly', 'monthly'], frequency)
请注意,如果您的频率不是列出的频率,这可能无法按预期工作。
我想查询 Table 和 return 给定行的 table 中最精细的频率。样本 table 和期望的结果如下。我已经尝试了查询的几次迭代,但还没有破解它。
"most granular frequency" 我的意思是我想 return 这个集合中任何行的第一个匹配 ['hourly', 'daily', 'weekly', 'monthly'] 作为名为 min_frequency
Table
----------------------------------
id | name | frequency
----------------------------------
----------------------------------
1 | apples | hourly
----------------------------------
2 | apples | daily
----------------------------------
3 | oranges | weekly
----------------------------------
4 | oranges | monthly
----------------------------------
想要的结果:
name | min_frequency
----------------------------------
----------------------------------
apples | hourly
----------------------------------
oranges | weekly
----------------------------------
当前尝试:
SELECT name, (
CASE
WHEN frequency='hourly' then frequency
WHEN frequency='daily' then frequency
WHEN frequency='weekly' then frequency
WHEN frequency='yearly' then frequency
END
) as min_frequency from Table
GROUP BY name, min_frequency
您可以将 distinct on
与条件排序逻辑一起使用:
select distinct on (name) *
from mytable
order by
name,
case frequency
when 'hourly' then 1
when 'daily' then 2
when 'weekly' then 3
when 'monthly' then 4
end
尽管您可以使用巨大的 case
表达式,但数组对此很方便:
select distinct on (name) t.*
from t
order by name,
array_position(array['hourly', 'daily', 'weekly', 'monthly'], frequency)
请注意,如果您的频率不是列出的频率,这可能无法按预期工作。