Skip to content

Instantly share code, notes, and snippets.

@havran
Last active February 8, 2017 05:09
Show Gist options
  • Save havran/1cfb5b9934f02fb460b342f9f73d4c50 to your computer and use it in GitHub Desktop.
Save havran/1cfb5b9934f02fb460b342f9f73d4c50 to your computer and use it in GitHub Desktop.
PostgreSQL - sort columns in row
-- Table: public.testy
-- DROP TABLE public.testy;
CREATE TABLE public.testy
(
id integer NOT NULL DEFAULT nextval('testy_id_seq'::regclass),
prod1 integer,
prod2 integer,
prod3 integer,
prod4 integer,
prod5 integer,
CONSTRAINT identities_pkey PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
INSERT INTO testy (id, prod1, prod2, prod3, prod4, prod5) VALUES (1, 13, 4, 10, 8, 23);
INSERT INTO testy (id, prod1, prod2, prod3, prod4, prod5) VALUES (2, 4, 5, 1, 8, 12);
SELECT
unnest(array['prod1', 'prod2', 'prod3', 'prod4', 'prod5']) AS "Values",
unnest(array[prod1, prod2, prod3, prod4, prod5]) AS "Count"
FROM testy
WHERE id = 1
ORDER BY "Count" DESC
LIMIT 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment