简体   繁体   English

选择最大不同值

[英]Selecting a max distinct value

I have a database table with a phone number (string) and a name (string) 我有一个数据库表,其中包含电话号码(字符串)和名称(字符串)

There same number may have different names in different rows 相同的数字在不同的行中可能具有不同的名称

given a certain number I want to select the most frequently used name 给定一定数量我想选择最常用的名称

For instance given the following data if using 555.1234 I should get back from the query Frank 例如,如果使用555.1234给出以下数据,我应该从查询Frank回来

Number   |  Name
-----------------
555.1234 |  Frank
555.1234 |  Fran
555.1234 |  James
555.1234 |  Frank
555.1233 |  Jesse

It seems like I should be able to combine distinct and Max somehow, but I can't come up with the right query to do this. 看起来我应该能够以某种方式将distinct和Max结合起来,但我无法想出正确的查询来做到这一点。 Any ideas? 有任何想法吗?

If you don't know what the phone number will be to pass into the query, then you can use the following: 如果您不知道将哪个电话号码传递给查询,则可以使用以下内容:

SELECT Number, Name, COUNT(Name) AS NameCount
FROM test
GROUP BY Number, Name
HAVING NameCount > 1
Order BY NameCount DESC
LIMIT 1

That will give you the most frequently used phone number by a single name, and return the phone, name and the count. 这将通过一个名称为您提供最常用的电话号码,并返回电话,姓名和计数。

Here is the test table that I used to try out the query, and the values thereof: 这是我用来尝试查询的test表及其值:

Number   | Name
555.1234 | Frank
555.1234 | Fran
555.1234 | James
555.1234 | Frank
555.1234 | Jesse
555.2234 | Frank
555.1234 | Jesse
555.1234 | Frank

Let me know if that works for you! 如果这对您有用,请告诉我!

If, as I understand the question, you have a specific number as input, then this may work depending on the database you are using. 如果我理解这个问题,你有一个特定的数字作为输入,那么这可能会取决于您使用的数据库。 Capsule's comment made me realize that might not be the situation. Capsule的评论让我意识到可能不是这种情况。 Edit Changed to Count(*) for (I think) better clarity based on Jack's good comment. 根据杰克的好评, 编辑改为计数(*)(我认为)更清晰。

select Top 1 Name, Count(*) total 
   from phone where number = '555.1234' 
   group by name 
   order by total desc

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

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