Consider the following three tables. A list of contacts, a list of status with a defined "rank" and a join table that links a contact to multiple status's.
CREATE TABLE public."Contacts"
(
name character varying COLLATE pg_catalog."default",
email character varying COLLATE pg_catalog."default",
contactid integer NOT NULL DEFAULT nextval('"Contacts_contactid_seq"'::regclass),
CONSTRAINT "Contacts_pkey" PRIMARY KEY (contactid)
)
CREATE TABLE public.statusoptions
(
option character varying COLLATE pg_catalog."default" NOT NULL,
"Rank" integer,
CONSTRAINT "ListOptions_pkey" PRIMARY KEY (option)
)
CREATE TABLE public."ContactStatus"
(
contactid integer NOT NULL,
option character varying COLLATE pg_catalog."default" NOT NULL,
CONSTRAINT "Options_pkey" PRIMARY KEY (contactid, option),
CONSTRAINT fk_1 FOREIGN KEY (contactid)
REFERENCES public."Contacts" (contactid) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION,
CONSTRAINT fk_2 FOREIGN KEY (option)
REFERENCES public.statusoptions (option) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION
)
The following query returns all rows.
select "Contacts".contactid, "Contacts".name, "ContactStatus".option, statusoptions."Rank" as
currentRank
from "Contacts","ContactStatus", statusoptions
where "Contacts".contactid = "ContactStatus".contactid
and statusoptions.option="ContactStatus".option
This returns a record set that looks like this:
Contactid name Status CurrentRank
1 "john" "apply" 1
1 "john" "Manager Review" 4
2 "bill" "apply" 1
2 "bill" "1st interview" 2
1 "john" "1st interview" 2
What I need is to create a query/view that would always JUST return the rows of the MAX current RANK. So the expected result I want from this view is:
Contactid name Status CurrentRank
1 "john" "Manager Review" 4
2 "bill" "1st interview" 2
At any time, I could change the "Rank" value in the statusoptions field, which would change the view accordingly.
Is this possible?