如何在SQL中查找最常出现的记录

时间:2018-07-13 01:38:54

标签: sql

我有一张雇员全名表,我需要检索与其频率相关的最常出现的名字,无论它是第一,第二还是第三。预期的结果就像第二张表一样

  <br><br>
    <table>

      <tr>
        <th>ID </th>
        <th>FirstName</th>
        <th>SecName</th>
        <th>ThirdName</th>
        <th>ForthName</th>
        <th>SixName</th>
      </tr>
      <tr>
        <td>1</td>
        <td>Sam</td>
        <td>John</td>
        <td>Mark</td>
        <td>Thomas</td>
        <td>William</td>
      </tr>
      <tr>
        <td>2</td>
        <td>Peter</td>
        <td>Wolf</td>
        <td>Sam</td>
        <td>Philip</td>
        <td>Sam</td>
      </tr>
      <tr>
        <td>3</td>
        <td>Mark</td>
        <td>Black</td>
        <td>Smith</td>
        <td>Luke</td>
        <td>Johnny
        </td>
      </tr>
    </table>
    <br> 
    <table>
      <tr>
        <th>Name </th>
        <th>Frq</th>
      </tr>
      <tr>
        <td>
          Sam</td>
        <td>3</td>
      </tr>
      <tr>
        <td>Mark</td>
        <td>2</td>
      </tr>
      <tr>
        <td> John</td>
        <td>1</td>
      </tr>
    </table>

等,然后其余具有相同频率的名称

2 个答案:

答案 0 :(得分:3)

您可以使用union allgroup by

select n.name, count(*)
from ((select FirstName as name from t) union all
      (select SecName as name from t) union all
      (select ThirdName as name from t) union all
      (select FourthName as name from t) union all
      (select SixthName as name from t) 
     ) n
group by n.name
order by count(*) desc
fetch first 1 row only;

答案 1 :(得分:2)

select Name,count(1) Frq from (
  select `FirstName` Name
  from T
  union all
  select `SecName` Name
  from T
  union all
  select `ThirdName` Name
  from T
  union all
  select `ForthName` Name
  from T
  union all
  select `SixName` Name
  from T
) AllT
group by Name
order by count(1) desc

TESTDDL

CREATE TABLE T
    (`ID` int, `FirstName` varchar(5), `SecName` varchar(5), `ThirdName` varchar(5), `ForthName` varchar(6), `SixName` varchar(7))
;

INSERT INTO T
    (`ID`, `FirstName`, `SecName`, `ThirdName`, `ForthName`, `SixName`)
VALUES
    (1, 'Sam', 'John', 'Mark', 'Thomas', 'William'),
    (2, 'Peter', 'Wolf', 'Sam', 'Philip', 'Sam'),
    (3, 'Mark', 'Black', 'Smith', 'Luke', 'Johnny')
;

结果:

|    Name | count(1) |
|---------|----------|
|     Sam |        3 |
|    Mark |        2 |
|   Smith |        1 |
| William |        1 |
|   Peter |        1 |
|  Thomas |        1 |
|  Johnny |        1 |
|  Philip |        1 |
|    John |        1 |
|    Luke |        1 |
|    Wolf |        1 |
|   Black |        1 |

TEST DEMO LINK