Order-By

Vertica UNION 和 ORDER BY

  • September 22, 2016

我想使用 ORDER BY 子句,但頂部仍然有一個特定條目。我認為這可能會做到,但 Vertica 忽略了第二個查詢中的 ORDER BY 子句:

(SELECT country_id, country_name 
FROM country_dim 
WHERE country_dim.iso_country_code LIKE 'US')
UNION 
(SELECT country_id, country_name 
FROM country_dim 
WHERE country_dim.iso_country_code NOT LIKE 'US' 
ORDER BY country_name ASC)

導致

12  United States of America
10  Germany
5   Brazil
6   Canada
7   China
8   France
4   Algeria
3   Aland Islands
2   Albania
8   Denmark
11  United Arab Emirates
13  Central African Republic
-1  Unknown
14  Svalbard and Jan Mayen

DDL 是

CREATE TABLE country_dim
(
   country_id int NOT NULL,
   iso_country_code char(2) NOT NULL,
   country_name varchar(512) NOT NULL,
   create_ts timestamptz,
   update_ts timestamptz
);

ALTER TABLE country_dim ADD CONSTRAINT country_dim_pk PRIMARY KEY (country_id) DISABLED;

查詢ORDER BY最終需要,而不是子查詢(請注意括號是可選的,至少在標準 SQL 中,不確定 Vertica 是否需要它們):

( SELECT country_id, country_name 
 FROM country_dim 
 WHERE iso_country_code LIKE 'US')
UNION 
( SELECT country_id, country_name 
 FROM country_dim 
 WHERE iso_country_code NOT LIKE 'US')     -- without ORDER BY
ORDER BY 
   CASE WHEN iso_country_code LIKE 'US' THEN 0 ELSE 1 END ASC,
   country_name ASC ; 

但是由於您要從同一個表中獲取所有數據,因此不需要 theUNION和子查詢:

SELECT country_id, country_name 
FROM country_dim 
ORDER BY 
   CASE WHEN iso_country_code LIKE 'US' THEN 0 ELSE 1 END ASC,
   country_name ASC ; 

引用自:https://dba.stackexchange.com/questions/150416