DROP TABLE abook;

CREATE TABLE
    abook (count, name, address)
AS SELECT
    DISTINCT ON(lower(address))
    CASE WHEN
        named.count IS NULL THEN 1
        ELSE named.count
    END,
    CASE WHEN
        named.name IS NULL THEN lower(unnamed.address)
        ELSE named.name
    END,
    lower(unnamed.address)
FROM
    contact unnamed
LEFT OUTER JOIN (
    SELECT
        DISTINCT ON (lower(address))
        count(name),
        name,
        lower(address) AS laddr
    FROM
        contact
    WHERE
        name != ''
    GROUP BY
        lower(address), name
    ORDER BY
        lower(address),
        count DESC,
        name
) named
ON
    named.laddr = lower(unnamed.address)
;
