I have a table that list email addressed for a member and has a boolean is_selected. The idea is that only one should be selected. I am joining the table to itself with a where clause on is_selected. I want to
string_agg(u.email, ',')
to show all the unselected emails in one column/row in a view.
Here is a fiddle.
My problem is that I can't get the view to work in cases where there are no entries that are unselected.
sql fiddle is having issues today so:
CREATE TABLE member_email
(
member integer NOT NULL, -- reference to another table
email character varying(150) NOT NULL,
is_selected boolean NOT NULL,
PRIMARY KEY(member,email)
);
INSERT INTO member_email
(member,email,is_selected)
VALUES
(2,'dax@example.com',TRUE),
(2,'oldemail@example.com',FALSE),
(2,'prevemail@example.com',FALSE),
(3,'rick@example.com',TRUE),
(3,'richard@example.com',FALSE),
(4,'bob@example.com',TRUE);
CREATE VIEW v_member_email AS
SELECT s.member
,s.email as selected_email
,string_agg(u.email, ',') as unselected_email
FROM member_email s
LEFT JOIN member_email u
ON s.member = u.member
WHERE s.is_selected = TRUE
AND u.is_selected = FALSE
GROUP BY s.member,s.email
ORDER BY member;
SELECT * FROM v_member_email;
-- where is bob@example.com in result?