我正在尝试获取以下查询以按城市的字母顺序显示结果,除了我希望“柏林”出现在列表顶部的事实
所以结果看起来像
希望有道理,
我目前有以下内容......
SELECT CompanyName, City
FROM customers
ORDER BY case when City = 'Berlin' END
答案 0 :(得分:16)
几乎:
SELECT CompanyName, City
FROM customers
ORDER BY CASE WHEN City = 'Berlin' THEN 0 ELSE 1 END, City
答案 1 :(得分:7)
SELECT CompanyName, City, CASE WHEN City = 'Berlin' THEN 0 ELSE 1 END AS Ordering
FROM customers
ORDER BY Ordering, City
答案 2 :(得分:2)
尝试类似
的内容SELECT CompanyName, City
FROM customers
ORDER BY case when City = 'Berlin' THEN 0 ELSE 1 END, City
答案 3 :(得分:1)
SELECT CompanyName, City
FROM customers
ORDER BY case when City = 'Berlin' then 1 else 999 END asc
答案 4 :(得分:1)
由于空白字符串首先出现在任何字符串有序列表中,所有其他结果都会正常排序。所以这很有效:
SELECT CompanyName, City
FROM customers
ORDER BY CASE WHEN City = 'Berlin' THEN '' ELSE City END
经过测试:
CREATE TABLE customers (CompanyName VARCHAR(50), City VARCHAR(50))
INSERT INTO customers VALUES ('Customer1', 'Berlin')
INSERT INTO customers VALUES ('Customer2', 'Algeria')
INSERT INTO customers VALUES ('Customer3', 'Australia')
INSERT INTO customers VALUES ('Customer4', 'Fiji')
INSERT INTO customers VALUES ('Customer5', 'Greece')
SELECT CompanyName, City
FROM customers
ORDER BY CASE WHEN City = 'Berlin' THEN '' ELSE City END
-- OUPUT
-- Customer1 Berlin
-- Customer2 Algeria
-- Customer3 Australia
-- Customer4 Fiji
-- Customer5 Greece
答案 5 :(得分:0)
如何使用Union?像这样的东西,例如:
SELECT 1 as Weight, CompanyName, City FROM customers
WHERE city='Berlin'
UNION ALL
SELECT 2 as Weight, CompanyName, City FROM
customers
WHERE city<>'Berlin'
ORDER BY Weight, City