I have a table with three filled columns named “Name”, “City” and “Occupation”.
I want to create a new column in the same table that contains the number of people who have the same occupation.
"Name" | "City" | "Occupation"
------------------------------
Amy | Berlin | Plumber
Bob | Berlin | Plumber
Carol | Berlin | Lawyer
David | London | Plumber
I want to have a table that contains:
"Name" | "City" | "Occupation" | "Number"
---------------------------------------
Amy | Berlin | Plumber | 2
Bob | Berlin | Plumber | 2
Carol | Berlin | Lawyer | 1
David | London | Plumber | 1
How does the SQL Query that creates the new columns have to look like? I want to actually create a new column in the database that I can access later.
Simple self-join:
If
Nameis a primary key you can just group by that alone instead, since the other columns would have a functional dependency on it. Of courseNamewouldn’t normally be a very good primary key.(You might need
COUNT(*)-1if you want the number of other people doing the job rather than the total. It’s unclear; the numbers in your example don’t add up either way.)If you must change your schema (and I wouldn’t recommend this kind of denormalisation unless you are absolutely certain you need it; see comments), you can do it with an UPDATE JOINed to Michael’s subselect: