DROP SCHEMA tmp CASCADE;
CREATE SCHEMA tmp ;
SET search_path=tmp;
CREATE TABLE yx
( Y INTEGER NOT NULL
, x CHAR NOT NULL
, PRIMARY KEY (y,x)
);
INSERT INTO yx (y,x) VALUES
(10,'b') ,(10,'d') ,(10,'e' ) -- y==10 does not have an 'a'
,(20,'b') ,(20,'a') ,(20,'d') -- y==20 does have an 'a'
;
--
-- using a CTE
--
WITH this AS (
SELECT y,x
, row_number() OVER (PARTITION by y ORDER BY (x='a') DESC, x ASC) AS rnk
FROM yx
)
SELECT this.y,this.x
FROM this
WHERE this.rnk = 1
;
--
-- with a subselect instead of a CTE
--
SELECT this.y,this.x
FROM (
SELECT y,x
, row_number() OVER (PARTITION by y ORDER BY (x='a') DESC, x ASC) AS rnk
FROM yx
) this
WHERE this.rnk = 1
;