简体   繁体   English

SQL计数查询,按多列分组

[英]SQL Count Query with Grouping by multiple Columns

I have a table with three filled columns named "Name", "City" and "Occupation". 我有一个包含三个填充列的表,名为“Name”,“City”和“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? 创建新列的SQL查询如何看起来像? I want to actually create a new column in the database that I can access later. 我想在数据库中创建一个我以后可以访问的新列。

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

Simple self-join: 简单的自我加入:

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

If Name is a primary key you can just group by that alone instead, since the other columns would have a functional dependency on it. 如果Name是主键,您可以仅依靠它进行分组,因为其他列将具有功能依赖性。 Of course Name wouldn't normally be a very good primary key. 当然Name通常不是一个非常好的主键。

(You might need COUNT(*)-1 if 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.) (你可能需要COUNT(*)-1如果你想要其他人做这份工作的数量而不是总数。目前还不清楚;你的例子中的数字不会相加。)

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: 如果你必须改变你的模式(我不推荐这种非规范化,除非你绝对确定你需要它;参见注释),你可以通过更新加入迈克尔的子选择:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM