我有一个像下面的查询得到错误 - 'SELECT DISTINCT,ORDER BY表达式必须出现在选择列表中'
select distinct name
from fruits
order by case
when name = 'mango' then 1
else 2
end
这会产生4条记录,比如说
apple, mango, pear and grape
我怎样才能确保我将Mango作为第一张唱片,其余的则随之而来。我尝试使用case语句,但无法获得所需的结果。任何想法将不胜感激。
答案 0 :(得分:3)
我相信这应该完成你所描述的需要。
select distinct
name,
case name when 'Mango' then 1 else 2 end as fruitOrder
from fruits
order by
fruitOrder
答案 1 :(得分:1)
如果您需要始终将'mango'
放在第一个位置,无论其他行如何,这可能是一种方式:
with fruits(name) as (
select 'apple' from dual union all
select 'mango' from dual union all
select 'pear' from dual union all
select 'grape' from dual
)
select name
from fruits
order by case
when name = 'mango' then 1
else 2
end
如果您需要添加DISTINCT
,这应该有效:
select distinct name,
case
when name = 'mango' then 1
else 2
end orderCol
from fruits
order by orderCol
答案 2 :(得分:0)
这将为您提供“芒果”,其他按顺序排列;
WITH get_rows AS
(SELECT DISTINCT item_type
FROM the_item)
SELECT item_type
FROM
(SELECT 1 as seq, item_type
FROM get_rows
WHERE item_type = 'Mango'
UNION ALL
SELECT 2 as seq, item_type
FROM get_rows
WHERE item_type <> 'Mango')
ORDER BY seq, item_type