Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select column values alternatively with predefined value order

Tags:

sql

postgresql

I have a table with these values and i want to show result with alternative values and also i want to change the order of values like customer 1, customer 3 ,customer 2 but they must be in alternative order. 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');

Desired Result:

    CUSTOMER 2
    CUSTOMER 1
    CUSTOMER 3
    CUSTOMER 2
    CUSTOMER 1
    CUSTOMER 3
    CUSTOMER 2
    CUSTOMER 1
    CUSTOMER 3

I have tried:

    SELECT  customername
    FROM    TEST
    ORDER BY ROW_NUMBER() OVER ( PARTITION BY customername ORDER BY  customername)

This returns,

    CUSTOMER 2
    CUSTOMER 1
    CUSTOMER 3
    CUSTOMER 2
    CUSTOMER 1
    CUSTOMER 3
    CUSTOMER 1
    CUSTOMER 3
    CUSTOMER 2

N.B Value can be integer like 3,2,1 because above is just an example


1 Answers

You need an additional table which defines the desired order:

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)    
like image 168
klin Avatar answered Dec 15 '25 10:12

klin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!