我有一个包含这些值的表格,我希望显示带有替代值的结果,并且我还想更改客户1,客户3,客户2等值的顺序,但它们必须按其他顺序排列。 customername。
CREATE TABLE TEST (
customername varchar(50)
);
INSERT INTO TEST VALUES('CUSTOMER 1');
INSERT INTO TEST VALUES('CUSTOMER 1');
INSERT INTO TEST VALUES('CUSTOMER 1');
INSERT INTO TEST VALUES('CUSTOMER 2');
INSERT INTO TEST VALUES('CUSTOMER 2');
INSERT INTO TEST VALUES('CUSTOMER 2');
INSERT INTO TEST VALUES('CUSTOMER 3');
INSERT INTO TEST VALUES('CUSTOMER 3');
INSERT INTO TEST VALUES('CUSTOMER 3');
期望的结果:
CUSTOMER 2
CUSTOMER 1
CUSTOMER 3
CUSTOMER 2
CUSTOMER 1
CUSTOMER 3
CUSTOMER 2
CUSTOMER 1
CUSTOMER 3
我试过了:
SELECT customername
FROM TEST
ORDER BY ROW_NUMBER() OVER ( PARTITION BY customername ORDER BY customername)
返回
CUSTOMER 2
CUSTOMER 1
CUSTOMER 3
CUSTOMER 2
CUSTOMER 1
CUSTOMER 3
CUSTOMER 1
CUSTOMER 3
CUSTOMER 2
N.B 值可以是3,2,1之类的整数,因为上面只是一个例子
答案 0 :(得分:1)
您需要一个额外的表来定义所需的顺序:
create table dict(customername varchar(50), priority int);
insert into dict values
('CUSTOMER 2', 1),
('CUSTOMER 1', 2),
('CUSTOMER 3', 3);
select customername
from test
join dict
using (customername)
order by
row_number() over (partition by customername),
priority;
customername
--------------
CUSTOMER 2
CUSTOMER 1
CUSTOMER 3
CUSTOMER 2
CUSTOMER 1
CUSTOMER 3
CUSTOMER 2
CUSTOMER 1
CUSTOMER 3
(9 rows)