如何在条件下订购SQL查询结果?

时间:2015-06-23 15:44:54

标签: sql postgresql conditional-statements

我有这个SQL查询:

DT <- 
  data.table(V1=paste("Day",1:5,sep="_"),V2=c(4,1,4,3,3),V3=c(4,1,5,4,2),V4=c(4,2,4,4,3))

给出了这个输出:

SELECT DISTINCT category FROM merchant ORDER BY category ASC

如何在结果的开头(或结尾)放置包含“general”的行?

2 个答案:

答案 0 :(得分:2)

CASE子句中使用ORDER BY表达式:

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

CASE保证首先排序General行。第二个参数按升序排序其余类别。

答案 1 :(得分:0)

你可以试试这个:

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