简体   繁体   English

SQL查询以获取一个字段重复另一个特定字段的次数

[英]SQL query to get number of times a field repeats for another specific field

Let's say I have two fields in a table. 假设我在一个表中有两个字段。 For the purpose of discussion let's say the fields are first name and last name. 出于讨论目的,我们假设这些字段是名字和姓氏。 I want to know how many times the first name shows up listed next to the same last name. 我想知道名字出现在同一个姓氏旁边列出的次数。 Assuming the last name column is unique, how do I figure out how many times each first name exists for each last name? 假设“姓氏”列是唯一的,我如何确定每个姓氏存在多少次?

ie let's say I have a table with the following data: 也就是说,假设我有一个包含以下数据的表:

Smith, John
Smith, David
Smith, Jane
Smith, John
Smith, John
Black, John
Black, Jane
Black, Jack
Black, Samantha
Black, Jack

I want a result that tells me that for Smith, there are 3 Johns, 1 David and 1 Jane, and for Black, there are 2 Jacks, 1 Jane and 1 Samantha. 我想要一个结果,告诉我史密斯有3个约翰,1个大卫和1个简,而布莱克有2个杰克,1个简和1个萨曼莎。

Not sure how to format the output best. 不知道如何最好地格式化输出。 Maybe simply: 也许很简单:

Smith, John, 3, David, 1, Jane, 1
Black, Jack, 2, Jane, 1, Samantha, 1

Something that would allow me to easily output something like: 可以让我轻松输出以下内容的内容:

Smith: John (3), David (1), Jane (1)
Black: Jack (2), Jane (1), Samantha (1)

It's important to note that it's possible that the second field can repeat, so counting unique instances in the column is not useful. 重要的是要注意,第二个字段可能会重复,因此对列中的唯一实例进行计数没有用。 It's only useful in reference to the first field. 仅在参考第一个字段时有用。

Thanks. 谢谢。

You can use a correlated sub-query in your SELECT statement and then wrap it all in a concat function to get the inline result you wanted 您可以在SELECT语句中使用相关的子查询,然后将其全部包装在concat函数中以获取所需的内联结果

SELECT  DISTINCT
        CONCAT(LastName, ': ', FirstName, '(', (SELECT COUNT(FirstName) FROM Person WHERE FirstName = p.FirstName AND LastName = p.LastName),')')
FROM    Person p

My solution: 我的解决方案:

select name,surname, count(surname) over (partition by name) as cnt
from your_table

You can use this. 您可以使用它。

SELECT CONCAT( Name,':', GROUP_CONCAT(CONCAT( LastName, ' (', CNT , ')' ), ' ') ) 
FROM (
  SELECT Name, LastName, COUNT(*) CNT FROM MyTable
  GROUP BY 
  Name, LastName
 ) T 
 GROUP BY Name

Sql Fiddle SQL小提琴

Result: 结果:

Black:Jane (1) ,John (1) ,Samantha (1) ,Jack (2)
Smith:David (1) ,Jane (1) ,John (3) 

Simple aggregation? 简单聚合?

select last_name, first_name, count(*)
from myTable
group by last_name, first_name
order by  last_name, first_name

Displaying it in a Smith, John, 3, David, 1, Jane, 1 format will probably fail because there are way too many Smiths with way too many different last names. Smith,John,3,David,1,Jane,1格式显示它可能会失败,因为存在太多Smith和太多不同姓氏的情况。

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

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