我有一个包含三个填充列的表,名为“Name”,“City”和“Occupation”。 我想在同一个表中创建一个新列,其中包含具有相同职业的人数。
"Name" | "City" | "Occupation"
------------------------------
Amy | Berlin | Plumber
Bob | Berlin | Plumber
Carol | Berlin | Lawyer
David | London | Plumber
我希望有一个包含以下内容的表:
"Name" | "City" | "Occupation" | "Number"
---------------------------------------
Amy | Berlin | Plumber | 2
Bob | Berlin | Plumber | 2
Carol | Berlin | Lawyer | 1
David | London | Plumber | 1
创建新列的SQL查询必须如何?我想在数据库中创建一个我以后可以访问的新列。
答案 0 :(得分:4)
select tbl.name, tbl.city, tbl.occupation, x.number
from tbl
join
(
select occupation, count(*) as number
from tbl
group by occupation
) as x on x.occupation = tbl.occupation
答案 1 :(得分:1)
简单的自我加入:
SELECT t0.Name, t0.City, t0.Occupation, COUNT(*) AS Number
FROM sometable AS t0
JOIN sometable AS t1 ON t1.Occupation=t0.Occupation
GROUP BY t0.Name, t0.City, t0.Occupation
如果Name
是主键,您可以仅依靠它进行分组,因为其他列将具有功能依赖性。当然Name
通常不是一个非常好的主键。
(如果你想要其他人的数量而不是总数,你可能需要COUNT(*)-1
。目前还不清楚;你的例子中的数字不会以任何方式加起来。)
如果你必须改变你的模式(我不推荐这种非规范化,除非你绝对确定你需要它;参见注释),你可以通过更新加入Michael的子选择来实现:
ALTER TABLE sometable ADD COLUMN Number INTEGER NOT NULL;
UPDATE sometable AS t0 JOIN (
SELECT Occupation, COUNT(*) AS Number
FROM sometable
GROUP BY Occupation
) AS t1 ON t1.Occupation=t0.Occupation
SET t0.Number= t1.Number;