简体   繁体   English

SQL在一个列中计算最常用的值,其中另一列等于某值。

[英]SQL Count most used value in one column where other column equals something.

This is a bit of a weird one I didn't know how to word the title please bear with me. 这有点奇怪,我不知道该如何写标题,请多多包涵。

So I have a table like this which stores data on different jobs: 因此,我有一个像这样的表,用于存储有关不同作业的数据:

id | company | contact
----------------------
0  |  name1  |  Bob
1  |  name1  |  Mark
2  |  name3  |  Sam
3  |  name1  |  Bob
4  |  name2  |  Nigel
5  |  name1  |  Bob
6  |  name3  |  Donald
7  |  name1  |  Sandy
8  |  name3  |  Nigel

Is there a query with SQL I can use to query the table to find out the most commonly used contact for a particular company. 是否有SQL查询,我可以使用该查询表查询特定公司的最常用联系人。

So the theoretical code I would be looking for would be something like: 因此,我要寻找的理论代码将类似于:

SELECT "Most Commonly used Contact" FROM table WHERE company = "$company";   

Is it possible in a single query or is this a multi query job? 是否可以在单个查询中进行,还是这是一个多查询工作?

try this sql query... 试试这个SQL查询...

SELECT *, COUNT(*) AS total 
FROM table 
WHERE company = '$company'
GROUP BY contact 
ORDER BY total DESC
LIMIT 1

Basically you want to find the number of contacts grouped by each company, and then grouped by the actual contact. 基本上,您想查找每个公司分组的联系人数量,然后再按实际联系人分组。 So in other words: 换句话说:

SELECT COUNT(`id`) as num_contacts, `contact`, `company` FROM `jobtable` GROUP BY `company`, `contact` ORDER BY `company`, num_contacts DESC

Or for a single company: 或对于单个公司:

SELECT COUNT(`id`) as num_contacts, `contact` FROM `jobtable` WHERE `company`='$company' GROUP BY `contact` ORDER BY num_contacts DESC

Gives you the single most used contact for $company, if you can't use LIMIT (eg if you are utilizing an Oracle Database): 如果您不能使用LIMIT(例如,如果您正在使用Oracle数据库),则为您提供$ company的最常用联系人:

SELECT contact, used_by
FROM (
  SELECT contact, COUNT(*) AS used_by
  FROM table
  WHERE company = $company
  GROUP BY contact
) t
HAVING used_by = MAX(used_by)

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

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