找到你要的答案

Q:How to order SQL query result on condition?

Q:如何在条件为SQL查询结果?

i have the this SQL query:

SELECT DISTINCT category FROM merchant ORDER BY category ASC

that gives this output:

accommodation
education
food
general
health
money
shopping
sport
transport

How to put the row that contains "general" at the start (or the end) of the result?

我有这个SQL查询:

SELECT DISTINCT category FROM merchant ORDER BY category ASC

这给出了这个输出:

accommodation
education
food
general
health
money
shopping
sport
transport

如何将包含“一般”的行放在结果的开始(或结束)?

answer1: 回答1:

Use CASE expression in ORDER BY clause:

SELECT category  
FROM (
  SELECT DISTINCT category 
  FROM merchant ) t
ORDER BY 
   CASE WHEN category = 'General' THEN 0 ELSE 1 END,
   category ASC 

CASE guarantees that rows with General will be sorted first. The second argument orders the rest of the categories in ascending order.

按子句使用用例表达式:

SELECT category  
FROM (
  SELECT DISTINCT category 
  FROM merchant ) t
ORDER BY 
   CASE WHEN category = 'General' THEN 0 ELSE 1 END,
   category ASC 

案例确保与一般的行将首先排序。第二个参数将其余类别按升序排列。

answer2: 回答2:

You can try this:

SELECT category 
FROM  merchant 
WHERE category = 'general'
UNION
SELECT DISTINCT category 
FROM merchant
WHERE category NOT IN ('general') 

你可以试试这个:

SELECT category 
FROM  merchant 
WHERE category = 'general'
UNION
SELECT DISTINCT category 
FROM merchant
WHERE category NOT IN ('general') 
sql  postgresql  order  condition